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

如何使所有AJAX调用顺序执行?,第1张

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

有比使用同步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 pre 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语言功能,因此这应该给您学习的良好动力。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5016238.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存