I have an existing project that has a lot of asynchronous functions that return promises. I\'m adding some caching so that in some cases the asynchronous functions will complet
Simply use return $.when();
to return an already resolved promise.
If you don't pass it any arguments at all, jQuery.when() will return a resolved promise.
Reference: https://api.jquery.com/jquery.when/
Notes:
return $.when(undefined);
which leads to the following rather cool trick which avoids any use of arrays and apply
.If you want to wait for a variable number of promises to complete in parallel then you can use this pattern in a loop:
var promise; // Undefined is treated as an initial resolved promise by $.when
while (insomeloop){
promise = $.when(promise, newpromise);
}
then make a final call on completion with:
promise.then(function(){
// All done!
});
e.g.
var promise;$.when
var $elements = $('.some-elements');
$elements.each(function(){
var $element = $(this).fadeout();
promise = $.when(promise, $element.promise());
});
promise.then(function(){
// All promises completed!
});
The downsides are minor:
when
wraps the previous promise in a new promise. A minor overhead and you no longer need to maintain and evaluate an array of promises.