如何使所有AJAX调用顺序?

Jad*_*ias 23 parallel-processing ajax jquery sequential jquery-deferred

我使用jQuery.而且我不希望在我的应用程序上进行并行AJAX调用,每个调用必须在开始之前等待之前的调用.怎么实现呢?有帮助吗?

更新如果有XMLHttpRequest或jQuery.post的任何同步版本,我想知道.但顺序!=同步,我想要一个异步和顺序的解决方案.

Tod*_*fee 16

除了使用同步ajax调用之外,还有一种更好的方法.Jquery ajax返回一个延迟,所以你可以使用管道链接来确保每个ajax调用在下一次运行之前完成.这是一个工作示例,您可以在jsfiddle上使用更深入的示例.

// How to force async functions to execute sequentially 
// by using deferred pipe chaining.

// The master deferred.
var dfd = $.Deferred(),  // Master deferred
    dfdNext = dfd; // Next deferred in the chain
    x = 0, // Loop index
    values = [], 

    // Simulates $.ajax, but with predictable behaviour.
    // You only need to understand that higher 'value' param 
    // will finish earlier.
    simulateAjax = function (value) {
        var dfdAjax = $.Deferred();

        setTimeout(
            function () {
                dfdAjax.resolve(value);
            },
            1000 - (value * 100)
        );

        return dfdAjax.promise();
    },

    // This would be a user function that makes an ajax request.
    // In normal code you'd be using $.ajax instead of simulateAjax.
    requestAjax = function (value) {
        return simulateAjax(value);
    };

// Start the pipe chain.  You should be able to do 
// this anywhere in the program, even
// at the end,and it should still give the same results.
dfd.resolve();

// Deferred pipe chaining.
// What you want to note here is that an new 
// ajax call will not start until the previous
// ajax call is completely finished.
for (x = 1; x <= 4; x++) {

    values.push(x);

    dfdNext = dfdNext.pipe(function () {
        var value = values.shift();
        return requestAjax(value).
            done(function(response) {
                // Process the response here.

            });

    });

}
Run Code Online (Sandbox Code Playgroud)

有些人评论说他们不知道代码的作用.为了理解它,您首先需要了解javascript承诺.我很确定承诺很快就会成为一个原生的javascript语言功能,所以这应该给你一个很好的学习动力.

  • @kamelkev,那不是完全正确的。设置`async:false`将防止在等待请求返回时触发代码中的其他事件。强烈建议不要这样做,因为即使单击等浏览器事件也不会触发。我提供的代码允许aysnc请求仍然以严格的顺序运行,但仍异步运行。 (2认同)

Nos*_*dna 6

你有两个我能想到的选择.一种是通过回调链接它们.另一种是使调用同步而不是异步.

您是否有理由要求它们顺序?这将减慢事情.

要使调用同步,您需要将Ajax调用中的async选项设置为false.请参阅http://docs.jquery.com/Ajax/jQuery.ajax#options上的文档(单击选项选项卡以查看它们).


Rm5*_*558 5

(async () => { 
  for(f of ['1.json','2.json','3.json']){
    var json = await $.getJSON(f);
    console.log(json)
 };
})()
Run Code Online (Sandbox Code Playgroud)
  1. 使用 jQuery ajax 调用请求 3 个 json 文件
  2. 使用await 按顺序(而不是并行)处理
  3. 适用于 Chrome/Firefox/Edge(截至 2018 年 1 月 30 日)

更多信息请参见MDN