Javascript Promises

Javascript Promises

2018-11-05 THUDM team Eunbi Choi

  1. Syntax

    new Promise( /* executor */ function(resolve, reject) { ... } );

    executor:

    A function that is passed with the arguments resolve and reject. The executor function is executed immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise constructor even returns the created object). The resolve and reject functions, when called, resolve or reject the promise, respectively.

  1. 3 states

    A Promise is in one of these states:

    • pending: initial state, neither fulfilled nor rejected.

    • fulfilled: meaning that the operation completed successfully.

    • rejected: meaning that the operation failed.

    A pending promise can either be fulfilled with a value, or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise's then method are called.

  2. Chaining

As the Promise.prototype.then() and Promise.prototype.catch() methods return promises, they can be chained.

  1. Methods

    Promise.all(iterable)

    Returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects.

    example:

    let filenames = ['index.html', 'blog.html', 'terms.html'];

    Promise.all(filenames.map(readFilePromise))
    .then(files => {
       console.log('index:', files[0]);
       console.log('blog:', files[1]);
       console.log('terms:', files[2]);
    });

    Promise.race(interable)

    Returns a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects, with the value or reason from that promise.

    example:

    function timeout(ms) {
     return new Promise((resolve, reject) => {
       setTimeout(reject, ms);
    });
    }

    Promise.race([readFilePromise('index.html'), timeout(1000)])
    .then(data => console.log(data))
    .catch(e => console.log("Timed out after 1 second"));

    Promise.reject(reason)

    Returns a Promise object that is rejected with the given reason.

    Promise.resolve(value)

    Returns a Promise object that is resolved with the given value.

  1. Catching and throwing errors

    We should consider all the code inside your then() statements as being inside of a try block. Both return Promise.reject() and throw new Error()will cause the next catch() block to run. A catch() block also catches the runntime error inside then() statement.

  1. Dynamic chains

    Sometimes we want to construct our Promise chain dynamically.

    example:

    function readFileAndMaybeLock(filename, createLockFile) {
     let promise = Promise.resolve();

     if (createLockFile) {
       promise = promise.then(_ => writeFilePromise(filename + '.lock', ''))
    }

     return promise.then(_ => readFilePromise(filename));
    }
  1. Running in series

    Sometimes we want to run the Promises in series, or one after the other. There's no simple method in Promise, but Array.reduce can help us.

    example:

    let itemIDs = [1, 2, 3, 4, 5];

    itemIDs.reduce((promise, itemID) => {
     return promise.then(_ => api.deleteItem(itemID));
    }, Promise.resolve());

    same as:

    Promise.resolve()
    .then(_ => api.deleteItem(1))
    .then(_ => api.deleteItem(2))
    .then(_ => api.deleteItem(3))
    .then(_ => api.deleteItem(4))
    .then(_ => api.deleteItem(5));
  1. Anti-patterns

    • Recreating callback hell

    • Failure to return

    • Calling .then() multiple times

    • Mixing callbacks and Promises

    • Not catching errors

 

references:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://medium.com/datafire-io/es6-promises-patterns-and-anti-patterns-bbb21a5d0918

转载于:https://www.cnblogs.com/THUDM/p/9912352.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值