问题
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.
回答1:
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.
回答2:
You cannot use await
, but actually I find jQuery's way of doing it quite intuitive, even the way they pass values
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();
$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
// v1, v2 and v3 output the resolve
// of d1, d2 and d3 respectively
console.log( v1, v2, v3 );
});
// done method of $.when will just run when
// all deferred functions are resolved,
// that is, after two seconds
setTimeout(()=>{d1.resolve()},1000);
setTimeout(()=>{d2.resolve("abc")},2000);
d3.resolve( 1, 2, 3, 4, 5 );
console.log('Begin...')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
来源:https://stackoverflow.com/questions/48978639/await-for-jquery-when-ajax-requests