ladar
ladar

Reputation: 5876

Return statement in promise's then

I'm learning Promises (vanilla es6 promises from this shim) and I have 2 functions, each of them is returning a new Promise and a 3rd function called magic(), that calls the 2 functions and also returns a Promise.

Sample code:

var CreatorX = {
    "create": function() {
        var p = new Promise(function(resolve, reject) {
            window.setTimeout(function() {
                window.console.log("created");
                resolve(22);
            }, 100);
        });
        return p;
    }
};

var CreatorY = {
    "create": function(id) {
        window.console.log("id " + id);
        var p = new Promise(function(resolve, reject) {
            window.setTimeout(function() {
                resolve(2244);
            }, 5);
        });
        return p;
    }
};

And here's the magic:

function magic() {
       return CreatorX.create().then(function(d) {
            CreatorY.create(d); // shouldn't it be 'return CreatorY...'?
        });
}

var r = magic();
r.then(function() {
    console.log("Done");
}, function(err){console.error("oops")});

My question is, why does this work? I don't have return statement at the line with CreatorY.create(d) in the magic function and yet it seems to work. Should the return be there? Is it just a coincidence that it works?

Upvotes: 2

Views: 3544

Answers (2)

edhedges
edhedges

Reputation: 2718

Your function magic() returns a promise so the CreatorY.create(d) call runs, but when you say r.then(... that is running the promise from the call to return CreatorX.create().then(...

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239653

When you return something from the Promise function, the promise is resolved with the value you return. The returned value from the promised function will be passed on to the chained promise function.

In your case, you are not returning anything explicitly. So, JavaScript will resolve the promise with undefined and that will be available to the

function() {
    console.log("Done");
}

function. But you are ignoring the resolved value from the previous promise. If you actually want to make use of it, then change the function to

function(result) {
    console.log(result);
}

Now you will be able to see the actual resolved value.

Upvotes: 2

Related Questions