0

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

3
  • Add more details related to you problem and things you have already tried to resolve issue. Commented Jan 1, 2016 at 15:22
  • Wow, a ton of things are wrong in your promise code. For one, your promises don't implement a then correctly since you cannot return a promise from the then, there is no error handling (a catch), and errors in the promise chain cannot be recovered from. Commented Jan 1, 2016 at 19:46
  • Have a look at some minimal "promise" libraries linked to here to see how far short your "implementation" of a well known spec really is Commented Jan 2, 2016 at 2:55

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This is it. Thanks so much.
@JasonDou If an answer solved your problem, please "accept" it with the checkmark next to it, so others can see, that the problem is solved.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.