• 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

  • 相关阅读:
    GridView编辑删除取消完整代码
    添加删除组件里没有IIS
    关于网站开发中存在的问题
    网络公司网站源码介绍Version1.0
    IIS 状态代码
    收藏常用的快捷方式
    连接池已经满的解决方案
    Do you choose a experienced employee with highsalary or a inexperienced employee with lowsalary?
    Registered Permanent residence/attitude for sports
    数据缓存依赖
  • 原文地址:https://www.cnblogs.com/tekkaman/p/7496790.html
Copyright © 2020-2023  润新知