手写promise实现异步

手写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) //2s后输出成功后的回调函数结果
}, 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 {
      //这里面是pending状态
            //将成功回调和失败回调存储起来
            this.successCallback = successCallback
            this.failCallback = failCallback
        }
    }
}
module.exports = MyPromise

3.node执行效果

手写promise实现异步_第1张图片

你可能感兴趣的:(promise,前端,js,javascript)