手写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执行效果

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值