jQuery$.每个嵌套在$.When中

jQuery $.each nested in $.When

本文关键字:When jQuery 嵌套      更新时间:2023-09-26

我有一个iten列表要通过一个返回$.ajax()的函数,但.done是在调用$.each之后被调用的,而不是在内部ajax调用完成之后!我该怎么办?!?

这是我的代码:

$.when(
    $.each(data, function (index, item) {
        GetReservation(
            item.UniqueId,
            apiRoot,
            //this is the 'success' function
            function (data2) {
                //do my stuff
            },
            //this is the 'error' function
            function (x, y, z) {
                if (x.status == 404) {
                    //OK, no reservations!
                }
            });
    })
).done(setButtons(box, c));

$.each并没有像您的代码所期望的那样返回一个promise数组。您应该先构建一个promise数组,然后用您的数组调用$.when

var promises = [];
$.each(data, function (index, item) {
    // add promise to array
    promises.push(GetReservation(
        item.UniqueId,
        apiRoot,
        //this is the 'success' function
        function (data2) {
            //do my stuff
        },
        //this is the 'error' function
        function (x, y, z) {
            if (x.status == 404) {
                //OK, no reservations!
            }
        }
    ));
})
$.when.apply($, promises).done(function(){
  setButtons(box, c)
});