Good day everyone,
I need to make multiple async calls and, if some fail, get which one(s) did and their error message. For this I have the following code :
$(function () {
function async1() {
var dfd = $.Deferred();
dfd.resolve('1');
return dfd.promise();
}
function async2() {
var dfd = $.Deferred();
dfd.reject('2');
return dfd.promise();
}
function async3() {
var dfd = $.Deferred();
dfd.reject('3');
return dfd.promise();
}
function buildMessage(v1, v2, v3) {
var msg = v1 != null ? v1 : "(v1 null)";
msg += v2 != null ? v2 : "(v2 null)";
msg += v3 != null ? v3 : "(v3 null)";
return msg;
}
var d1 = async1();
var d2 = async2();
var d3 = async3();
$.when(d1, d2, d3).done(function (v1, v2, v3) {
$('#done').html(buildMessage(v1, v2, v3));
}).fail(function (v1, v2, v3) {
$('#fail').html(buildMessage(v1, v2, v3));
});
});
Here the JSFiddle with this code: https://jsfiddle.net/bjyfhave/8/
In jQ, the callback function in .done() has the resolved values as parameters (v1, v2, v3). If you replace the dfd.reject by .resolve in async2 and async3, it works great.
I followed the same logic for the .fail() and was expecting this result :
(v1 null)23
But instead I get:
3(v2 null)(v3 null)
Which means that I get the last rejection as 1st argument and the other ones are lost.
I failed to find any working examples of this situation, which leads to my question :
How to get all rejections of multiples async methods running simultaneously ?
Thank you for your help.
The reason that you are getting the result 3(v2 null)(v3 null), is because fail() is called as soon as any promise in the list fails. This means that if async3() fails first, then .fail() will be called, and 3 will be the only argument passed to the callback.
Just to restate, fail() does not receive the result of all promises, just the first rejection.
How to get all rejections of multiples async methods running simultaneously ?
Well the difficulty here is that your expected output seems to be synchronous (result of A, then B, then C). If the order doesn't matter, then you can just run separate .done() functions for each one, and print out the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With