小编典典

如何使所有AJAX调用顺序执行?

ajax

我使用jQuery。而且我不想在我的应用程序上进行并行AJAX调用,每个调用都必须等待上一个调用之后才能开始。如何执行呢?有帮手吗?

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


阅读 284

收藏
2020-07-26

共1个答案

小编典典

有比使用同步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.

            });

    });

}

有些人说他们不知道代码做什么。为了理解它,您首先需要了解javascript
promises。我敢肯定,诺言很快就会成为本地javascript语言功能,因此这应该给您学习的良好动力。

2020-07-26