js常见面试题——详解Promise使用与原理及实现过程,Web毕业设计项目

console.log(res)
return 2
},
err => {}
)
.then(
res => {
console.log(res)
},
err => {}
)

我们首先要实现一个 Promise 的类,这个类的构造函数会传入一个函数作为参数,并且向该函数传入 resolve 和 reject 两个方法。
初始化 Promise 的状态为 pending。

class MyPromise {
constructor(executor) {
this.executor = executor
this.value = null
this.status = ‘pending’

const resolve = value => {
if (this.status === ‘pending’) {
this.value = value // 调用 resolve 后记录 resolve 的值
this.status = ‘fulfilled’ // 调用 resolve 扭转 promise 状态
}
}

const reject = value => {
if (this.status === ‘pending’) {
this.value = value // 调用 reject 后记录 reject 的值
this.status = ‘rejected’ // 调用 reject 扭转 promise 状态
}
}

this.executor(resolve, reject)
}

(2)接下来要实现 promise 对象上的 then 方法,then 方法会传入两个函数作为参数,分别作为 promise 对象 resolve 和 reject 的处理函数。
这里要注意三点:

  • then 函数需要返回一个新的 promise 对象
  • 执行 then 函数的时候这个 promise 的状态可能还没有被扭转为 fulfilled 或 rejected
  • 一个 promise 对象可以同时多次调用 then 函数

class MyPromise {
constructor(executor) {
this.executor = executor
this.value = null
this.status = ‘pending’
this.onFulfilledFunctions = [] // 存放这个 promise 注册的 then 函数中传的第一个函数参数
this.onRejectedFunctions = [] // 存放这个 promise 注册的 then 函数中传的第二个函数参数
const resolve = value => {
if (this.status === ‘pending’) {
this.value = value
this.status = ‘fulfilled’
this.onFulfilledFunctions.forEach(onFulfilled => {
onFulfilled() // 将 onFulfilledFunctions 中的函数拿出来执行
})
}
}
const reject = value => {
if (this.status === ‘pending’) {
this.value = value
this.status = ‘rejected’
this.onRejectedFunctions.forEach(onRejected => {
onRejected() // 将 onRejectedFunctions 中的函

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值