一、Promise的基础知识
1、Promise的生命周期
内部属性[[PromiseState]]被用来表示Promise的3中状态:"pending"、"fulfilled"、"rejected".
所有的Promise都有then()方法,它接受两个参数:第一个是当Promise的状态为fulfilled时要调用的函数;第一个是当Promise的状态为rejected时要调用的函数。then()的两个参数都是可选的。例如:

Promise还有一个catch()方法,它和上面示例代码中的最后一个then()方法是等价的。例如:

2、创建未完成的Promise
用Promise构造函数可以创建新的Promise,构造函数只接受一个参数:包含初始化Promise代码的执行器函数。例如下面的代码:

上面的代码就用Promise包裹了一个Node.js的fs.readFile()异步调用,如果失败,执行器向reject()函数传递错误对象;如果成功,执行器向resolve()函数传递文件内容。
3、创建已处理的Promise
(1)使用Promise.resolve(),该方法只接受一个参数并返回一个完成态的Promise。例如:

(2)使用Promise.reject()方法,该方法创建已拒绝的Promise。例如:

4、执行器错误
如果执行器内部抛出一个错误,则Promise的拒绝处理程序就会被调用。例如:

二、全局的Promise拒绝处理
Promise的特性决定了很难检测一个Promise是否被处理过。所以Node.js和浏览器环境都做出了一些改变来解决这个问题。
(1)Node.js环境的拒绝处理
处理Promise拒绝时会触发process对象的两个事件:
* unhandledRejection 在一个事件循环中,当Promise被拒绝,并且没有提供拒绝处理程序时,触发该事件。
* rejectionHandled 在一个事件循环后,当Promise被拒绝时,若拒绝处理程序被调用,触发该事件。
设计这些事件是用来识别那些被拒绝却又没被处理过的Promise的。例如:

(2)浏览器环境的拒绝处理
其实和Node.js相似,只是使用上面会不同,例如下面的代码:

三、串联Promise
每次调用then()或者catch()方法时实际上创建并返回了另一个Promise,只有当第一个Promise完成或者被拒绝后,第二个才会被解决。例如:

1、捕获错误
Promise链可以用来捕获错误,例如:

2、Promise链的返回值
Promise链的另一个重要特性是可以给下游Promise传递数据。例如:

3、在Promise链中返回Promise
在Promise间可以返回Promise对象,例如:

四、响应多个Promise
1、Promise.all()方法
Promise.all()方法只接受一个参数并返回一个Promise,该参数是一个含有多个受监视Promise的可迭代对象,只有所有Promise都被解决了,返回的Promise才会被解决。例如:

2、Promise.race()方法
这个方法与all方法不同的是,只要有一个Promise被解决返回的Promise就被解决了,例如:

五、自Promise继承
Promise与其他内建类型一样,也可以作为基类派生其他类,所以定义自己的Promise变量来扩展内建Promise的功能。例如:

网友评论