js常见面试题——详解Promise使用与原理及实现过程,2024年前端开发者常见面试题

对于以上完成的 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 { <

  • 22
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值