// promise手写
/*
1.promise状态 pending(等待) resolve(成功) reject(失败)
2. resolve 和 reject 函数
3. then方法的实现
4.发布订阅者模式 实现异步
5.链式调用 ( 返回 普通值 和 promise)
6.resolve reject all race catch finally
*/
const resolvePromise = (promise, x, resolve, reject) => {
if (promise == x) {
return reject(
new TypeError('Chaining cycle detected for promise #<promise>')
)
}
if (typeof x == Object && x != null || typeof x == 'function') {
let called //添加一个开放 state 只能改变一次
try { // 获取then失败则直接rejecet(err)
let then = x.then
if (typeof then == 'function') {
then.call(x, res => {
// resolve(res) //采用promise的成功结果,并且向下传递
if (called) return
called = true
resolvePromise(promise, res, resolve, reject)
}, rej => {
if (called) return
called = true
reject(rej) //采用promise的失败结果,并且向下传递
})
} else {
if (called) return
called = true
resolve(x) //x不是一个函数是个对象
}
} catch (err) {
if (called) return
called = true
reject(err)
}
} else {
resolve(x) // x是一个普通的值
}
}
class MyPromise {
constructor(executor) {
this.state = 'pedding' //状态
this.value = undefined //成功返回的值
this.reason = undefined //失败返回的值
this.onResolvedCallbacks = [] //成功的回调队列
this.onRejectCallbacks = [] // 失败的回调队列
//成功的回调函数
let resolve = (value) => {
if (this.state === 'pedding') {
this.state = 'resolved'
this.value = value
// 发布执行成功的函数
this.onResolvedCallbacks.forEach(fn => fn())
}
}
let reject = (reason) => {
if (this.state === 'pedding') {
this.state = 'rejected'
this.reason = reason
// 发布执行失败的函数
this.onRejectCallbacks.forEach(fn => fn())
}
}
try {
//执行new Promise(callback) 中的callback
executor(resolve, reject)
} catch (err) {
// 失败直接返回失败的值
reject(err)
}
}
resolve = (value) => {
return new MyPromise((resolve, reject) => {
resolve(value)
})
}
reject = (reason) => {
return new MyPromise((resolve, reject) => {
reject(reason)
})
}
// then方法的实现
then(onResolved, onRejected) {
// 递归实现链式调用
let promise = new MyPromise((resolve, reject) => {
let x
// 状态为resolve,执行onResolved,传入成功的值
if (this.state == 'resolved') {
setTimeout(() => {
try {
x = onResolved(this.value)
// 添加一个resolvePromise()的方法来判断x跟promise的状态
//决定promise是走成功还是失败
resolvePromise(promise, x, resolve, reject)
} catch (err) { //中间任何一个环节报错都要走reject()
reject(err)
}
}, 0);
}
// 状态为rejected,执行onRejected,传入失败的值
if (this.state == 'rejected') {
setTimeout(() => {
try {
x = onRejected(this.reason)
resolvePromise(promise, x, resolve, reject)
} catch (err) {
reject(err)
}
}, 0);
}
// 异步 存储回调函数
if (this.status == 'pending') {
// 在pending状态 订阅成功失败的回调函数
this.onResolvedCallbacks.push(() => {
setTimeout(() => {
try {
x = onResolved(this.value)
resolvePromise(promise, x, resolve, reject)
} catch (err) {
reject(err)
}
}, 0);
})
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
x = onRejected(this.reason)
resolvePromise(promise, x, resolve, reject)
} catch (err) {
reject(err)
}
}, 0);
})
}
})
return promise
}
}
Promise 实现
最新推荐文章于 2022-07-22 10:40:38 发布