Deferred in $.when while looping an array

2019-09-06 08:26发布

问题:

I have the following code:

var arrOutfit = []; // will be filled
...
$.when(

  $.each(arrOutfit, function(key, sAdd) {

    $.post('/checkout/addArticle', 'sAdd=' + sAdd + '&sQuantity = 1');

  });

).then() {

  // something

}

But this does not work. I figured that the array loop is invalid. As you can see I have mutliple ajax calls and I want to have just one callback, so I know, when all requests has been done. How can I achieve this?

Any ideas will be appreciated.

Best regards

回答1:

Your usage of $.when is not quite correct. Try this:

var arrOutfit = [], // will be filled
    promises = [];

// ...

$.each(arrOutfit, function(key, sAdd) {
    promises.push($.post('/checkout/addArticle', 'sAdd=' + sAdd + '&sQuantity = 1'));
});

$.when.apply($, promises).then(function(schemas) {
    // something...
});

Note that the each is used to populate an array with promises which are then provided to the when which will execute once they are all complete.