对于以上完成的 MyPromise 进行测试,测试代码如下
const p = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve(1)
}, 1000)
})
p.then(res => {
console.log(‘first then’, res)
return res + 1
}).then(res => {
console.log(‘first then’, res)
})
p.then(res => {
console.log(second then
, res)
return res + 1
}).then(res => {
console.log(second then
, res)
})
/**
- 输出结果如下:
- first then 1
- first then 2
- second then 1
- second then 2
*/
(3)在 promise 相关的内容中,有一点常常被我们忽略,当 then 函数中返回的是一个 promise 应该如何处理?
考虑如下代码:
// 使用正确的 Promise
new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 1000)
})
.then(res => {
console.log(‘外部 promise’)
return new Promise((resolve, reject) => {
resolve(内部 promise
)
})
})
.then(res => {
console.log(res)
})
/**
- 输出结果如下:
- 外部 promise
- 内部 promise
*/
通过以上的输出结果不难判断,当 then 函数返回的是一个 promise 时,promise 并不会直接将这个 promise 传递到下一个 then 函数,而是会等待该 promise resolve 后,将其 resolve 的值,传递给下一个 then 函数,找到我们实现的代码的 then 函数部分,做以下修改:
then(onFulfilled, onRejected) {
const self = this
if (this.status === ‘pending’) {
return new MyPromise((resolve, reject) => {
this.onFulfilledFunctions.push(() => {
const thenReturn = onFulfilled(self.value)
if (thenReturn instanceof MyPromise) {
// 当返回值为 promise 时,等该内部的 promise 状态扭转时,同步扭转外部的 promise 状态
thenReturn.then(resolve, reject)
} else {
<