博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Javascript Promises
阅读量:7152 次
发布时间:2019-06-29

本文共 3390 字,大约阅读时间需要 11 分钟。

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://www.cnblogs.com/THUDM/p/9912352.html

你可能感兴趣的文章
Atitit. 软件开发中的管理哲学--一个伟大的事业必然是过程导向为主 过程导向 vs 结果导向...
查看>>
JS产生随机数的几个用法!
查看>>
浏览器默认样式(User Agent Stylesheet)
查看>>
所有Mac用户都需要知道的9个实用终端命令行
查看>>
Java Persistence with MyBatis 3(中国版) 第五章 与Spring集成
查看>>
Java虚拟机详解04----GC算法和种类【重要】
查看>>
Receiver type for instance message is a forward
查看>>
将SALT_STACK的JOB-CACHE放到数据库中,而建库用DJANGO的ORM完成
查看>>
GPIO推挽输出和开漏输出详解
查看>>
I18N、L10N、G11N
查看>>
引用类中的enum
查看>>
影响网站打开速度的9大因素
查看>>
HTML5之废弃和更新的元素与属性
查看>>
[转]asp.net解决高并发的方案.
查看>>
(转)unity中基于alpha通道的shadow volume实现
查看>>
linux下svn的co如何排除目录
查看>>
项目中最常用到的颜色
查看>>
[转]10个学习Android开发的网站推荐
查看>>
CI框架 -- 开发环境、生产环境
查看>>
命令行解析器
查看>>