Promise类加入异步逻辑
2021-12-12 本文已影响0人
湘兰沅芷
settimeout会影响主进程不会立即执行,执行器函数会立即执行,不会等待settimeout的执行,执行then函数会处于pendding的状态;在pending状态下保存resolve和reject的回调,当执行resolve或reject的时候,执行successCallback或者failcallback函数返回结果。
const PENDING = 'pending' // 等待
const FULFILLED = 'fulfilled' // 成功
const REJECTED = 'rejected'// 失败
class MyPromise {
constructor(executor) {
executor(this.resolve, this.reject)
}
status = PENDING
value = undefined
reason = undefined
successCallback = undefined
failCallback = undefined
resolve = value => {
if (this.status !== PENDING) return
// 将状态修改为成功
this.status = FULFILLED
// 保存成功之后的值
this.value = value
this.successCallback && this.successCallback(this.value)
}
reject = reason => {
if (this.status !== PENDING) return
this.status = REJECTED
this.reason = reason
this.failCallback && this.failCallback(this.reason)
}
then(successCallback, failCallback) {
if (this.status === FULFILLED) {
successCallback(this.value)
} else if (this.status === REJECTED) {
failCallback(this.reason)
} else {
// 等待
// 讲成功回调和失败回调进行存储
this.successCallback = successCallback
this.failCallback = failCallback
}
}
}
module.exports = MyPromise
const MyPromise = require('./myPromise')
let promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功')
}, 2000)
// resolve('成功')
// reject('失败')
})
promise.then(value => {
console.log(value)
}, reason => {
console.log(reason)
})