处理jQuery ajax异步调用的最佳方法是什么?

时间:2013-10-28 14:50:23

标签: jquery ajax design-patterns asynchronous

我最近开始使用重型客户端jQuery / javascripts的项目。我正在努力让其中一个屏幕工作。

我的功能如下:

function init{
  populateTypes();
  populateGroups();
  populateStatuses();
  applyCurrentUserSettings();
}

所有populate*方法都会向服务器发出ajax调用($.ajax),并在视图上查看一些复选框列表。 applyCurrentUserSettings方法还会生成ajax请求并在视图上设置当前用户选择。

问题是populate*方法是异步的,并且通过调用applyCurrentUserSettings方法,复选框列表“有时”为空,并且apply方法失败。

我可以通过在async: false调用中传递$.ajax或将每个ajax调用链接到另一个调用中来获得此工作,但我想知道是否有更好的方法/设计模式来处理这样的问题场景。

3 个答案:

答案 0 :(得分:4)

您可以让所有函数返回延迟并使用$.whenhttp://api.jquery.com/jQuery.when/

function populateTypes () {
    //your code
    return $.ajax(...);
}


$.when(populateTypes(), populateGroups(), ...).then(applyCurrentUserSettings);

答案 1 :(得分:0)

我相信您可以使用ajaxComplete()来延迟applyCurrentUserSettings的触发器,直到查询完成。

答案 2 :(得分:0)

构建你的函数,以便它们正确地返回promise对象,然后使用.then方法将多个一个接一个地链接,或者使用.when方法发送x个,然后在所有这些完成时执行某些操作

function populateTypes () {
    //your code
    return $.ajax(...);
}

以下每次发送1个:

function init () {
    populateTypes().then(populateGroups)
        .then(populateStatuses)
        .then(applyCurrentUserSettings)
        .done(function(){
            console.log("all done");
        });
}

以下内容会立即发送除最后一个之外的所有内容,以及前三个结束后的最后一次发送:

function init () {
    $.when(populateTypes(), populateGroups(), populateStatuses())
        .then(applyCurrentUserSettings)
        .done(function(){
            console.log("all done");
        });
}