Deferred in $.when while looping an array

左心房为你撑大大i 提交于 2019-12-11 18:16:15

问题


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.



来源:https://stackoverflow.com/questions/25865869/deferred-in-when-while-looping-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!