javascript实现一个简单的Promise

代码:

function Promise(creator){
    this.status = "pending";
    this.reason = null;
    this.data = null;

    const _this = this;

    var resolve = function(data){
        if(_this.status == "pending"){
            _this.data = data;
            _this.status = "resolved";
        }
    }

    var reject = function(e){
        if(_this.status == "pending"){
            _this.reason = e;
            _this.status = "rejected";
        }
    }

    creator(resolve, reject);
}

Promise.prototype.then = function(res,rej){
    const _this = this;
    if(_this.status == "resolved"){
        res(_this.data);
        return ;
    }
    if(_this.status == "rejected"){
        res(_this.reason);
        return ;
    }
}

调用:

new Promise(function(resolve, reject){
    resolve("hello world");
}).then(function(data){
    console.log(data);
});

输出:

> hello world
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容