Question

I'm currently using jQuery 1.9.1.

I'm busy chaining two promises so that they both execute before the result is processed, but I only care about passing the second promise's result over to callers.

My first attempt was below (please also ignore that I'm not handling error cases):

function doSomething() {
    var firstPromise = $.Deferred(function(dfd) { dfd.resolve(1); }).promise();
    var secondPromise = $.Deferred(function(dfd) { dfd.resolve(2); }).promise();

    var grouped = $.when(firstPromise, secondPromise);

    grouped.then(function(firstResult, secondResult){
        return secondResult;
    });

    return grouped
}

doSomething.then(function(a, b) {
    console.log(arguments); // will be [1, 2], correspondingly a=1, b=2
});

But as can be seen, it's not only the second result that is returned, but both results. I initially thought that because the group.then returns only secondResult, that only this would be passed to the caller.

My second attempt solves the issue, but needs to use another deferred to achieve this:

function doSomething() {
    var firstPromise = $.Deferred(function(dfd) { dfd.resolve(1); }).promise();
    var secondPromise = $.Deferred(function(dfd) { dfd.resolve(2); }).promise();

    var grouped = $.when(firstPromise, secondPromise);

    var promise = $.Deferred(function(dfd) {
        grouped.then(function(a, b) { 
            dfd.resolve(b);
        });
    }).promise();

    return promise;
}

doSomething().then(function(result) {
    console.log(result); // will be 2
});

Here I just create a new promise that resolves with only with the second result of the grouped promise, and return that promise instead.

This is all fine and well, but is there perhaps an easier way to do this with jQuery promises?

Was it helpful?

Solution

Your problem is in the return grouped line (in the first code example).

You're returning the original grouped promise, not the result of the .then call.

.then doesn't modify the passed promise, it creates a new one, but you're discarding that.

It should be:

function doSomething() {
    var firstPromise = $.Deferred(function(dfd) { dfd.resolve(1); }).promise();
    var secondPromise = $.Deferred(function(dfd) { dfd.resolve(2); }).promise();

    var grouped = $.when(firstPromise, secondPromise);

    return grouped.then(function(firstResult, secondResult){
        return secondResult;
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top