实现Promise类

基本使用:

let promise = new Promise((resolve, reject) => {
    // do something
    if (true) {
       resolve('success');
    } else {
        reject('fail');
     }
})
promise.then((res)=> {
    console.log(res);    // 如果成功输出:'success'
}, (err)=> {
    console.log(err);     // 如果失败输出:'fail'
})    

那么如何自己实现上面的这样一个Promise类呢?

class Promise {
    constructor(executor) {
        this.status ='pending';    // 初始状态默认设为pending
        this.value = undefined;
        this.reason = undefined;
        let resolve = (value) => {
            if(this.status === 'pending') {    // 只有状态为pending才能转换状态
                this.value = value;       // 将传递进来的值赋给value保存
                this.status = 'resolved';    // 将状态设置成resolved
            }
        }
        let reject = (reason) => {
            if(this.status === 'pending') {
                this.reason = reason;    // 将传递进来的失败原因赋给reason保存
                this.status = 'rejected';   // 将状态设置成rejected
            }
        }
        executor(resolve, reject);    // 默认执行executor
    }
    then(onFulfilled, onRejected) {
        if(this.status === 'resolved') {
            onFulfilled(this.value);    // 执行成功的resolve,并将成功后的值传递过去
        }
        if(this.status === 'rejected') {
            onRejected(this.reason);   //执行失败的reject,并将失败的原因传递过去
        }
    }
}
module.exports = Promise;     // 导出Promise
原文地址:https://www.cnblogs.com/xuepei/p/9070807.html