简体   繁体   中英

what's wrong with my javascript promise code

I want to implement a javascript promise by myself to understand the mechanism, here is my code, but it report undefined error, could someone help me to take a look?

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")});

You can run by node

you lose the binding between defer and resolve() in the setTimeout() callback.

One solution would be to use bind() :

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

You lose the binding between defer and resolve() in the setTimeout() callback, as mentioned in the other answer. Now you can use ()=> instead of function() to maintain the current binding since ES6.

setTimeout(()=>{remoteCall(defer.resolve)}, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM