I had a simple script working using Promises
in ECMA6 but I'm now converting what I wrote to jQuery to be compatible for all browsers but the issue I'm having is that availableDevices
contains an array of AJAX responses rather an array of product names like the script is telling it to.
Basically when all AJAX requests inside $.each have finished, I need to run a function with that data. What am I missing? (It's been a while since I wrote anything with jQuery...)
var availableDevices = [];
$.each(products, function (index, product) {
availableDevices.push($.ajax({
type: 'GET',
url: 'http://localhost:1337/api/product_availability?__url_path_param=' + formatProductName(product.product_name),
complete: function (response) {
if (response.status == 200) {
return formatProductName(product.product_name);
}
}
}));
});
$.when(availableDevices).then(function (data) {
console.log(data);
});
There is no need to store the result of each call inside a separate array, you have access to each response via the then
method:
var requests = [];
$.each(products, function (index, product) {
requests.push($.ajax({
type: 'GET',
url: 'http://localhost:1337/api/product_availability?__url_path_param=' + formatProductName(product.product_name)
}));
});
$.when.apply($, requests).then(function() {
console.log(arguments.length + " results returned");
for(var i=0;i<arguments.length;i++){
var arg = arguments[i];
console.log(arg);
}
});
Live example (using jsfiddle json echo for demo): http://jsfiddle.net/vzq4Lwm8/
Having read your comment, there is a better solution, using a combination of $.Deferred()
and the complete
function on an $.ajax
call:
var deferreds = $.map(products, function (product) {
var formattedProduct = formatProductName(product)
var defer = $.Deferred();
$.ajax({
type: 'GET',
url: 'http://localhost:1337/api/product_availability?__url_path_param=' + formattedProduct,
complete: function (response) {
if (response.status == 200) {
defer.resolve(formattedProduct);
}
else{
defer.resolve(null);
}
}
})
return defer;
});
$.when.apply($, deferreds).then(function() {
console.log(arguments.length + " results returned");
var availableProducts = $.map(arguments, function(x) { return x });
// availableProducts will only contain items which returned 200 response
});
Live demo: http://jsfiddle.net/vzq4Lwm8/1/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments