function Promiss(fn) {
this.state = ‘pending‘ //当前状态
this.value = null // 成功执行时得到的数据
this.reason = null // 执行失败时的返回值
this.resolveCallbacks = [] // 存储回调函数的数组
this.rejectCallbacks = []
resolve = value => {
this.state = ‘resolver‘
this.value = value
this.resolveCallbacks.map(cb => cb(this.value))
}
reject = reason => {
this.state = ‘rejected‘
this.value = value
this.resolveCallbacks.map(cb => cb(this.reason))
}
try {
fn(resolve, reject)
} catch (error) {
reject(error)
}
}
Promiss.prototype.then = function (onFulfilled, onRejected) {
if (this.state === ‘pending‘) {
this.resolveCallbacks.push(onFulfilled)
this.rejectCallbacks.push(onRejected)
}
}
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(‘ok‘)
}, 2000)
})
.then(res => {
console.log(res);
})
原文:https://www.cnblogs.com/peaky/p/promies.html