How do you use .when().then() to trigger a function when using deffered objects in the .when()?

我们两清 提交于 2019-12-04 09:21:37

I recently applied something similar.

when() expects a deferred object or list of deferred objects, but if you want to use an array, you need to use apply().

replace

$.when(XHRs)

with

$.when.apply(null, XHRs)

If this does not work, you might need to wrap your Ajax call in a function:

function SendAjax(data){
return $.ajax({Options as they are in your ajax call});
}

and then push them to XHRs as such:

XHRs.push(SendAjax(data));

the following is how I implemented this in my code, you can adapt this if needed:

//We want to notify how many memberships have been made after they're all made. since they're async, we'll need to use promises
//however, because we repeat the same ajax call with different parameters, we need to push them to an array and then apply() them.
checkedBoxes.each(function () {
    createArray.push(CreateMembershipsAjax(this));
});
//we did the work before we start creating them, so show some progress;
add1ToProgress();
$.when.apply(null, createArray).done(function () {
    //this function will only start once all ajax calls have been successfull.
    divCreated.append(membershipCount + " memberships created:");
    MembershipsCreated = true;
    window.close();
});

...

CreateMembershipsAjax(element){
    //process element, create Data from it;
    return $.ajax({option});
}

And yes, the comments are actually in my code and not just added for clarification on this page.

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