Best way to get a promise in jQuery?
When programming with promises in jQuery, I sometimes need to start with resolved promises, especially when chaining .then()
in a loop like this, as shown in method # 2 in this answer :
data.reduce(function(p, item) {
return p.then(function() {
return print(item);
});
}, $.Deferred().resolve().promise());
So, I know I can get a promise with this:
$.Deferred().resolve().promise()
But that seems ugly and wasteful (three function calls). Is there a better way (less code, less function calls) to get the resolved promise in jQuery, or a better way to write my loop .reduce()
above?
source to share
For starters, you don't need one .promise
. Deferred jQuery objects are already and promises , so $.Deferred().resolve()
will work as well.
In my opinion this is the best approach with jQuery since it is explicit, however there are shorter paths around it. The shortest I know:
$().promise(); // shorter but more hacky.
$.Deferred().resolve(); // this will work and is what I'd do
$.when(); // this is also a viable alternative
This is short enough. Of course, it is best to use the best promise library when you can, as jQuery promises does not guarantee well-ordered asynchronous execution and does not allow error handling in addition to being very slow if you have a lot of promises running.
Of course, no one bothers you to write a utility method :)
source to share