What I am trying to achieve is sending a bunch of post requests to a print service, and if any of them fail I want to display a warning message to the user. My current set up has a warning message for each time it fails.
items.forEach(function (item) {
var data = {
date: self.getDateTime(),
barcode: item.barcode,
description: item.description
};
var url = 'http://localhost/print_service'
$.ajax({
method: "POST",
url: url,
data: JSON.stringify(data),
}).fail(function () {
self.display_warning(
'Failed to connect to printer',
);
});
});
I am not able to make use of async / await in this project.
My thought was to just set some flag like printFailed = true
, and after the loop just display a message if it is true. However, the fail is of course asyncronous, so the flag is now set when I make that check.
How can I tackle this effectively? Typically I would throw the error and / or flag into a .then()
, but I can't do this as it would then still be caught in the loop.
CodePudding user response:
Try to use Promise.all
:
const requests = items.map(function(item) {
return $.ajax({
method: "POST",
url: 'http://localhost/print_service',
data: JSON.stringify({
date: self.getDateTime(),
barcode: item.barcode,
description: item.description
}),
});
});
Promise.all(requests).catch(function() {
self.display_warning('Failed to connect to printer', );
});