如何使所有的AJAX调用的顺序? [英] How to make all AJAX calls sequential?

查看:125
本文介绍了如何使所有的AJAX调用的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery。我不希望我的应用程序并发AJAX调用,每次调用必须等待的previous开始之前。如何实现呢?有任何帮助?

I use jQuery. And I don't want concurrent AJAX calls on my application, each call must wait the previous before starting. How to implement it? There is any helper?

更新如果存在的XMLHtt prequest或jQuery.post我想知道的任何同步版本。但是,连续的!=同步,和我想的异步和时序解决方案。

UPDATE If there is any synchronous version of the XMLHttpRequest or jQuery.post I would like to know. But sequential != synchronous, and I would like an asynchronous and sequential solution.

推荐答案

还有一个更好的方法比使用同步Ajax调用做到这一点。 jQuery的AJAX返回一个延迟,所以你可以只使用管道链接,以确保每一个AJAX调用下一个运行之前完成。这里有一个工作的例子有更深入的例子中,你可以上的jsfiddle 的播放。

There's a much better way to do this than using synchronous ajax calls. Jquery ajax returns a deferred so you can just use pipe chaining to make sure that each ajax call finishes before the next runs. Here's a working example with a more in depth example you can play with on 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.

            });

    });

}

有些人评论说,他们不知道什么是code一样。为了了解它,你首先需要了解JavaScript的承诺。我是pretty的肯定承诺很快成为本地JavaScript语言特性,所以应该给你一个很好的学习积极性。

Some people have commented they have no clue what the code does. In order to understand it, you first need to understand javascript promises. I am pretty sure promises are soon to be a native javascript language feature, so that should give you a good incentive to learn.

这篇关于如何使所有的AJAX调用的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆