手写Promise

2021-03-24  本文已影响0人  曾祥辉

一、Promise 是一个异步操作返回的对象,用来传递异步操作的消息。

Promise 介绍和使用详见:MDN对Promise的介绍

一句话概括就是:Promise对象用于表示一个异步操作的最终完成 (或失败)及其结果值

二、根据自己对 Promise 的理解,实现一个Promise :

Promise 有三种状态:Pending 初始态; Fulfilled 成功态; Rejected 失败态。


let Promise = (executor) => {

    let that= this;

    that.status = 'pending'; //等待态

    that.value = undefined;  //成功的返回值

    that.reason = undefined; //失败的原因

    function resolve(value){

        if(that.status === 'pending'){

            that.status = 'resolved';

            that.value = value;

        }

    }

    function reject(reason) {

        if(that.status === 'pending') {

            that.status = 'rejected';

            that.reason = reason;

        }

    }

    try{

        executor(resolve, reject);

    }catch(e){

        reject(e);// 捕获时发生异常,就直接失败

    }

}

//onFufiled 成功的回调

//onRejected 失败的回调

//用来指定 Promise 对象的状态改变时要执行的操作
Promise.prototype.then =  (onFufiled, onRejected)=> {

    let that= this;

    if(that.status === 'resolved'){

        onFufiled(that.value);

    }

    if(that.status === 'rejected'){

        onRejected(that.reason);

    }

}
export default { Promise };

测试样例

import Promise from './Promise'
let promise = new Promise((resolve, reject) => {
    resolve("成功回调");
})

promise.then((res) => {
    console.log('res:', res);
},(err) => {
    console.log('err:', err);
})
上一篇下一篇

猜你喜欢

热点阅读