I've looked at your API and this example but I don't quite understand its usage.
var def1 = $.Deferred();
var def2 = $.Deferred();
var def3 = $.Deferred();
var p1 = def1.promise();
var p2 = def2.promise();
var p3 = def3.promise();
$.when(p1, p2, p3).done(function(rs1, rs2, rs3) {
LOG('When complete: '+rs1+', '+rs2+', '+rs3); // Results are in the order of the promises, regardless of the order they resolved in
});
def1.resolve('foo');
def3.resolve('bar');
setTimeout(function() {
def2.resolve('AJAX!'); // No output is sent until this one returns
}, 2000);
function LOG(msg) {
$('#log').append('<p>'+msg+'</p>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="details">
An example of using <tt>when()</tt> to wait for all promises
</div>
<div id="log"></div>
Does anyone know how it works?
As usual in
jQuery
, the behavior of the functionwhen
varies according to the parameters used, but in the case you propose it is the same as that ofPromise.all
:That is, it groups promises together and creates a new promise that will resolve when all the grouped promises have resolved.
This is useful, for example, when you need to make several calls
AJAX
and you need them all to complete before performing an action, but you don't want to chain them because they can be executed in parallel. In this way you save time and the code is cleaner:Its vanilla Javascript equivalent would be (note the square brackets, the parameters are grouped in a
array
):