Promise 表示一个异步 *** 作的状态和结果。通过 Promise规范 来学习其实现过程,有利于我们更好地掌握和使用它。
resolve 方法 如果 Promise 是 pending,则将状态改为 fulfilled将 Promise 的 value 赋值为 resolve 参数如果有 onFulfilledCallback,则将其推到微队列中(onFulfilledCallback 见下文) then 方法 如果 Promise 是 pending 状态, 将 then 的 onFulfilled 方法追加保存到 Promise 的 onFulfilledCallback,即规范中的 PromiseFulfillReactions 列表末尾。将 then 的 onFulfilled 方法追加保存到 Promise 的 onRejectedCallback,即规范中的PromiseRejectReactions 列表后边。 如果 Promise 是 fulfilled 状态 把 onFulfilled 推到 microtask 微任务队列中 如果 Promise 是 rejected 状态 把 onRejected 推到 microtask 微任务队列中 例子现在让我们通过一个例子,来理解上面的内容。请回答以下程序的打印内容。
setTimeout(() => {
console.log(0)
}, 0);
let p1 = new Promise((resolve, reject) => {
resolve({name: 1})
})
let p2 = p1.then(
() => {
console.log(1)
}
)
let p3 = p2.then(value => {
console.log(2)
})
let p4 = new Promise((resolve, reject) => {
resolve('Promise')
})
let p5 = p4.then(
value => {
console.log(3)
},
error => console.log(error)
)
let p6 = p5.then(value => {
console.log(4)
})
console.log(5)
解析
// 1. 把定时器任务推到宏队列中
// 13.执行宏队列,打印 0
setTimeout(() => {
console.log(0)
}, 0);
// 2. 调用 resolve,此时 p1 的状态变为 fulfilled
let p1 = new Promise((resolve, reject) => {
resolve({name: 1})
})
// 3. 执行 then,把 onFulfilled 推到微队列
// 9. 执行微队列,打印 1
// 9. p2 状态变为 fulfilled, 将 p2 的 onFulfilledCallback 推到微队列
let p2 = p1.then(
() => {
console.log(1)
}
)
// 4. 执行 then,p2 是 pending 状态,所以保存 onFulfulled 到 P2 的 onFulfilledCallback 中
// 11. 执行微队列,打印 2
let p3 = p2.then(value => {
console.log(2)
})
// 5. 调用 resolve,此时 p4 的状态变为 fulfilled
let p4 = new Promise((resolve, reject) => {
resolve('Promise')
})
// 6. 执行 then,把 onFulfilled 推到微队列
// 10. 执行微队列,打印 3
// 10. p5 状态变为 fulfilled, 将 p5 的 onFulfilledCallback 推到微队列
let p5 = p4.then(
()=> {
console.log(3)
},
error => console.log(error)
)
// 7. 执行 then,p5 是 pending 状态,所以保存 onFulfulled 到 p5 的 onFulfilledCallback 中
// 12. 执行微队列,打印 4
let p6 = p5.then(value => {
console.log(4)
})
// 8. 输出 5
console.log(5)
打印结果:5 1 3 2 4 0
参考资料 ECMAScript® 2016 Language Specification Promise resolve functionsECMAScript® 2016 Language Specification Promise.prototype.thenECMAScript® 2016 Language Specification Properties of Promise InstancesPromises/A+欢迎分享,转载请注明来源:内存溢出
评论列表(0条)