Javascript jQuery$。每个嵌套在$。中时

Javascript jQuery$。每个嵌套在$。中时,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有一个iTen列表要通过一个返回$.ajax()的函数传递,但是.done在$之后被调用。每个都被调用,而不是在内部ajax调用完成之后!我该怎么办 这是我的密码: $.when( $.each(data, function (index, item) { GetReservation( item.UniqueId, apiRoot, //this is the 'success' function

我有一个iTen列表要通过一个返回
$.ajax()
的函数传递,但是
.done
$之后被调用。每个
都被调用,而不是在内部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));

$。每个
都不会像您的代码所期望的那样返回承诺数组。您应该首先构建承诺数组,然后调用
$。使用数组时

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)
});

$。每个
都不会像您的代码所期望的那样返回承诺数组。您应该首先构建承诺数组,然后调用
$。使用数组时

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)
});

这是预期的行为…将处理程序添加到ajax。据我所知,这可能是相关的;当您使用
$时。当
时,您的所有承诺都应该成功,以便
$。当
返回完成时。@Liam不是真的。。它可能相关,但不是真的重复。看这里:这是预期行为…将处理程序添加到ajax中。据我所知,这可能是相关的;当您使用
$时。当
时,您的所有承诺对于
$应该是成功的。当
返回完成时。@Liam不是真的。。它可能是相关的,但不是真的重复。看这里:问题仍然存在。。。setButtons仍然在GetReservation完成之前被调用…我立即看到了问题,setButtons被立即调用,需要包装在函数中。我已经更新了示例。另外,请确保您的
GetReservation
函数正在返回承诺。无需查看更多源代码(特别是
GetReservation
函数,很难说。如果您使用的是一系列承诺,那么以这种方式调用
$.when
肯定会起作用,例如:
$.when.apply($,[$.get('example.html'),$.ajax({..})]。done(…)
。因此假设
GetReservation
正在执行类似于
return$.ajax(…)的操作
它应该可以工作。问题仍然存在……在GetReservation完成之前,setButtons仍然被调用……我立即看到了问题,setButtons被立即调用,需要包装到函数中。我已经更新了示例。另外,请确保您的
GetReservation
函数正在返回承诺。无需查看mo如果您使用的是一系列承诺,那么以这种方式调用
$.when
肯定会起作用,例如:
$.when.apply($,[$.get('example.html'),$.ajax({..})]。done(..)
。因此,假设
GetReservation
正在执行类似于
return$.ajax(…)
的操作,它应该可以正常工作。