我的javascript承诺代码有什么问题

时间:2016-01-01 15:18:38

标签: javascript promise

我想自己实现一个javascript承诺来理解机制,这里是我的代码,但它报告了未定义的错误,有人可以帮我看看吗?

var Promise = function(){
    this.successesCallback = [];
}

Promise.prototype.then = function(success){
    console.log("add success");
    this.successesCallback.push(success);
}

var Defer = function(){
    this.promise = new Promise();
}

Defer.prototype.resolve = function(){
    console.log("defer resolve is calling");
    console.log("2promise of defer:" + this.promise)
    this.promise.successesCallback[0]();
}

var remoteCall = function(callBack){
    for(var i = 0; i < 1000000000; i++){
    }
    callBack();
}

var callRemote = function(){
    var defer = new Defer();
    console.log("promise of defer:" + defer.promise)
    console.log("set timer for remote call");
    setTimeout(function(){remoteCall(defer.resolve)}, 0);
    console.log("remote call is triggered");

    return defer.promise;
}

callRemote().then(function(){console.log("Hello, server call done")});

您可以按节点

运行

2 个答案:

答案 0 :(得分:2)

您在defer回调中失去了resolve()setTimeout()之间的约束力。

一种解决方案是使用https://jsfiddle.net/cz57tzb8/22/

setTimeout(function(){remoteCall(defer.resolve.bind( defer )}, 0);

答案 1 :(得分:0)

您在resolve()回调中失去setTimeout()()=>之间的绑定,如其他答案中所述。现在,您可以使用function()代替setTimeout(()=>{remoteCall(defer.resolve)}, 0); 来维护自ES6以来的当前绑定。

{{1}}