jquery – How does when() work?

Question:

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?

Answer:

As usual in jQuery , the behavior of the when function varies depending on the parameters used, but in the case you raise it is the same as that of Promise.all :

let p1= new Promise(function (resolver) {
  setTimeout(()=> resolver('medio segundo'), 500);
});
let p2= new Promise(function (resolver) {
  setTimeout(()=> resolver('1 segundo'), 1000);
});
let p3= new Promise(function (resolver) {
  setTimeout(()=> resolver('2 segundos'), 2000);
});

$.when(p1,p2,p3).then( (r1,r2,r3) => {
  console.log('Todo resuelto:',r1,r2,r3);
});
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

That is, it groups promises together and creates a new promise that will resolve when all the grouped promises have resolved.

It is useful, for example, when you need to make several AJAX calls 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. This way you save time and the code is cleaner:

let peticion1 = $.ajax(....);
let peticion2 = $.ajax(...);

$.when(peticion1,peticion2).then(function (respuesta1,respuesta2) { ... });

Its vanilla Javascript equivalent would be (note the square brackets, the parameters are grouped in an array ):

let peticion1=fetch(...);
let peticion2=fetch(...);

Promise.all([peticion1, peticion2]). then(function ([res1,res2]) => {...});
Scroll to Top