手写Promise

一、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);
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容