手写promise2:promise实现异步
1.promise异步效果
const MyPromise = require('./promiseUtils/myPromise')
let promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 2000)
})
promise.then(value => {
console.log(value)
}, reason => {
console.log(reason)
})
2.promise异步实现代码
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class MyPromise {
constructor (excutor) {
excutor(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
3.node执行效果