zoukankan      html  css  js  c++  java
  • Using promises

    Using promises

      过去,异步方法这样写:

    function successCallback(result) {
      console.log("It succeeded with " + result);
    }
    
    function failureCallback(error) {
      console.log("It failed with " + error);
    }
    
    doSomething(successCallback, failureCallback);
    View Code

      使用promise后,异步方法这样写:

    let promise = doSomething(); 
    promise.then(successCallback, failureCallback);
    View Code

      promise模式有以下几个好处:

      1、回调方法永远在下一帧后才会调用。即使当前帧已完成。

      2、可以通过串连.then,设置多个回调。

      promise模式可以用于解决死亡金字塔问题:

    doSomething(function(result) {
      doSomethingElse(result, function(newResult) {
        doThirdThing(newResult, function(finalResult) {
          console.log('Got the final result: ' + finalResult);
        }, failureCallback);
      }, failureCallback);
    }, failureCallback);
    View Code
    doSomething().then(function(result) {
      return doSomethingElse(result);
    })
    .then(function(newResult) {
      return doThirdThing(newResult);
    })
    .then(function(finalResult) {
      console.log('Got the final result: ' + finalResult);
    })
    .catch(failureCallback);
    View Code

      catch(failureCallback) 是 then(null, failureCallback) 的简单写法

      使用new Promise((resolve, reject)=>{})创建 Promise。Basically, the promise constructor takes an executor function that lets us resolve or reject a promise manually

    const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
    
    wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback);
    View Code
    new Promise((resolve, reject) => {
        console.log('Initial');
    
        resolve();
    })
    .then(() => {
        throw new Error('Something failed');
            
        console.log('Do this');
    })
    .catch(() => {
        console.log('Do that');
    })
    .then(() => {
        console.log('Do this whatever happened before');
    });
    View Code

      Promise.resolve() and Promise.reject() are shortcuts to manually create an already resolved or rejected promise respectively

      以下两段代码均为reduce应用。用于串于执行异步或同步调用。

    [func1, func2].reduce((p, f) => p.then(f), Promise.resolve());
    View Code
    Promise.resolve().then(func1).then(func2);
    View Code

    参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

  • 相关阅读:
    Codeforces 1163E 高斯消元 + dfs
    Codeforces 1159E 拓扑排序
    Codeforces 631E 斜率优化
    Codeforces 1167F 计算贡献
    Codeforces 1167E 尺取法
    Gym 102007I 二分 网络流
    Codeforces 319C DP 斜率优化
    Codeforces 1163D DP + KMP
    Comet OJ
    Vue 的响应式原理中 Object.defineProperty 有什么缺陷?为什么在 Vue3.0 采用了 Proxy,抛弃了 Object.defineProperty?
  • 原文地址:https://www.cnblogs.com/tekkaman/p/7496790.html
Copyright © 2011-2022 走看看