Zoltán Tamási Zoltán Tamási - 28 days ago 12
jQuery Question

How can I redirect a promise to an existing deferred?

I have a function which returns a promise. I create a jQuery deferred for this purpose, which might be resolved/rejected in custom ways, depending on implementation.

One implementation uses an AJAX call, and there I'd like to redirect or queue the failure/resolution of the AJAX promise to the one which was created earlier. This means that whenever the AJAX call has a resolve/reject/progress, the deferred should trigger its own resolve/reject/progress too with the same arguments.

Here is some dummy sample code.

function Test() {
}

Test.prototype.doSomething() {
this._deferred = $.Deferred();
this.doSomethingImpl();
return this._deferred;
}

var test = new Test();
test.doSomethingImpl = function() {
var ajax = $.post(...);
// resolve/reject/progress here the this._deferred based on the ajax promise
}


I know I can do it in a verbose way using the AJAX
done
,
fail
and
progress
callbacks, and manually call my deferred's corresponding method (
resolve
,
reject
or
progress
), but I'm seeking for kind of a one-liner, if there is any.

Answer

Yes, it would be possible to redirect the resolution (in a perfect world1, just deferred.resolve(promise)), but it's completely unnecessary. Don't create deferreds when you're already calling something that produces a promise for you - avoid the deferred antipattern! You can simply return that very promise:

Test.prototype.doSomething = function() {
    return this.doSomethingImpl();
};

var test = new Test();
test.doSomethingImpl = function() {
    var ajax = $.post(...);
    return ajax; // the promise
};

1) where jQuery follows the Promises/A+ specification and deferred.resolve accepts thenables