Say you have the following piece of code:
function someProcess() {
var deferred = $.Deferred();
apiCall(function (recvData) {
deferred.resolveWith(null, [recvData]);
});
return deferred.promise();
}
function mainFunction() {
$.when(someProcess())
.then(someOtherProcess);
}
In this example I only need to wait for a single deferred to be resolved. In this case, what is the difference (if any) between writing the second function as above versus writing it like this:
function mainFunction() {
someProcess()
.then(someOtherProcess);
}
I mean, I like writing it the first way because it makes it clear that we’re using jQuery deferred objects, but I’m curious if it’s necessary in this case.
edit: I fixed a typo in the then() call. Thanks for catching that.
edit: Thanks for the answer nrabinowitz. I think you have nailed the points that I was not sure about in regard to using when() vs. using a raw jQuery deferred object instance. I went and fixed my code again to return a promise instead of the entire deferred object. That is how I do it in my actual code right now, just forgot to add it here.
I haven’t used custom Deferred objects, but my understanding is that there are two differences in your examples:
Using
$.when()allows you to arbitrarily add more deferred objects to be handled by your handlers. Obviously, not a big deal, since you’d have to change that line of code either way to add more deferreds.$.when()only gets the Promise object, not the whole deferred object, which if I understand correctly is a consistency measure to hide the deferred’s state-changing methods (e.g.resolve()), only exposing handler hooks and state inspection methods. This seems like good practice, but in your example you could do the same thing by callingsomeProcess().promise()instead of$.when(someProcess()).So I think you’re right – both methods will work, but the main benefit of using
$.when()is to make the code more legible and set expectations appropriately for other programmers. Using either$.when()ordeferred.promise()will additionally help protect against some less competent coder messing with the state of your deferred in a confusing way.