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

  • 相关阅读:
    Timer 函数 C#
    【学习笔记】 golang的插件 创建share object
    mongodb数组操作
    mongo数据库的表设计原则:二
    mongodb + nginx 存储照片方案
    mongodb聚合操作$使用例子
    mongo配置复制集
    尼采全集
    java日志框架
    常用包收集
  • 原文地址:https://www.cnblogs.com/tekkaman/p/7496790.html
Copyright © 2011-2022 走看看