Search code examples
jqueryajaxpromiseasync-await.when

await for jQuery.when ajax requests


This code inside async function, does not give the expected result:

var result = await $.when( $.get('/api/1'), $.get('/api/2') );

with one request, result will be the output I expect (the response text). However, with these two requests, the returned result is an array which does not hold the two Promises values. Is there any workaround?
I know there are then() and done(), but I prefer using await.


Solution

  • jQuery's .when() and the native await have different semantics. Compare:

    // jQuery
    
    $.when(promise1, promise2).done(function (result1, result2) {
        // work with result1 and result2
    });
    

    and

    // native
    
    Promise.all([promise1, promise2]).then(function (results) {
        // work with results[0] and results[1]
    });
    
    // await is just a variation of the above:
    
    var results = await Promise.all([promise1, promise2]);
    // work with results[0] and results[1]
    

    The native implementation uses a single array of multiple promises, while jQuery's implementation expects multiple individual promises.

    This means that you can't use await with $.when(). await effectively gives you the value of the first argument to the callback when the asynchronous function completes.

    Using await for Promise.all() works, because the first argument will be an array of all results. Using await for $.when() won't work, because the second result will be the second argument to the callback, and so on, which means you would lose all results except the first one.

    jQuery's implementation predates native promises, they designed it this way and now they have to stick with it. Such is life.