// excutor:可以理解为传入一个函数为执行器
function myPromise(excutor) {
// 1. 执行结构
let self = this
self.status = 'pending' // 状态
self.value = null //成功的值
self.reason = null //失败原因
// 8. 添加缓存数组
self.onFulfilledCallbacks = []
self.onRejectedCallbacks = []
// 成功 4.判断状态做相应处理
function resolve(value) {
if (self.status === 'pending') {
self.value = value //保存成功结果
self.status = 'fulfilled'
// 10. 状态改变,依次取出
self.onFulfilledCallbacks.forEach(item => item(value))
}
}
// 失败
function reject(reason) {
if (self.status === 'pending') {
self.reason = reason //保存失败原因
self.status = 'rejected'
// 10. 状态改变,依次取出
self.onRejectedCallbacks.forEach(item => item(reason))
}
}
// 3.执行一遍
try {
excutor(resolve, reject)
} catch (error) {
reject(error)
}
}
//2. then 关联到原型链上
myPromise.prototype.then = function (onFulfilled, onRejected) {
// 5.状态改变,调用then方法
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : function (data) { resolve(data) }
onRejected = typeof onRejected === 'function' ? onRejected : function (err) { throw err }
// 9. 先添加进去
let self = this
if (self.status === 'pending') {
self.onFulfilledCallbacks.push(onFulfilled)
self.onRejectedCallbacks.push(onRejected)
}
}
let demo = new myPromise((resolve, reject) => {
console.log("打印出内容")
//6. 尝试异步
setTimeout(() => {
resolve('异步成功')
}, 500)
})
// 执行 7.异步失败
demo.then(data => console.log(data)) //异步成功
标签:function,status,resolve,self,onFulfilled,reason,Promise,手写
From: https://www.cnblogs.com/chic-life/p/17698915.html