如何使所有 AJAX 调用按顺序进行?
-
18-09-2019 - |
题
我使用 jQuery。我不希望在我的应用程序上进行并行 AJAX 调用,每个调用都必须等待前一个调用才能开始。如何实施?有帮忙的吗?
更新 如果有任何同步版本的 XMLHttpRequest 或 jQuery.post 我想知道。但顺序!=同步,我想要一个异步和顺序的解决方案。
解决方案
有一个更好的方法来做到这一点比使用同步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的承诺。我敢肯定的承诺是即将成为本地JavaScript语言功能,因此,应该给你一个很好的激励学习。
其他提示
您有,我能想到的两种选择。一种是通过回调来把它们连。另一种是使同步而不是异步调用。
你有什么希望他们连续的理由吗?这将慢下来。
要拨打电话同步,您将设置在Ajax调用假async选项。查看文档在 http://docs.jquery.com/Ajax/jQuery.ajax#options (点击选项标签以查看它们)。
您可以给叙述的JavaScript尝试 http://www.neilmix.com/narrativejs/doc /
我从来没有使用,虽然它自己。如果我想做到这一点,我会建立某种抽象为链的异步操作。正如其他人所说,而它的等待响应正在处理来自Ajax对象块事件的synchonous版本。这会导致浏览器看起来它冻结,直到它临危响应。
你可以做到这一点的最好办法是通过链接回调为Nosredna说。我不建议使用同步XMLHttpRequest的,因为他们锁定您的整个应用程序。
有没有太多的帮手这个据我知道,但你可以做一些类似的回调FIFO。
看这个: http://docs.jquery.com/Ajax/jQuery.ajax (单击“选项”选项卡)。
但请记住,同步调用将冻结页面,直到收到响应为止,因此它不能在生产站点中使用,因为如果出于任何原因必须在浏览器冻结的情况下等待 30 秒,用户会生气。
编辑:好的,通过您的更新,您想要实现的目标会更清楚;)
因此,您的代码可能如下所示:
$.getJSON("http://example.com/jsoncall", function(data) {
process(data);
$.getJSON("http://example.com/jsoncall2", function (data) {
processAgain(data);
$.getJSON("http://example.com/anotherjsoncall", function(data) {
processAgainAndAgain(data);
});
});
});
这样,只有在接收并处理了对第一个调用的响应后才会发出第二个调用,只有在接收并处理了对第二个调用的响应后才会发出第三个调用。此代码适用于 getJSON,但可以适用于 $.ajax。
同步调用并不一定要慢,如果你有一个应用程序,其中AJAX调用open,员额,然后关闭套接字,多次调用该插座是没有意义的一些插座只能处理一个连接,在这种情况下,排队的数据,因此它仅在发送之前的AJAX调用完成意味着更高的数据吞吐量。
(async () => {
for(f of ['1.json','2.json','3.json']){
var json = await $.getJSON(f);
console.log(json)
};
})()
- 请求3压文件有文化的阿贾克斯的电话
- 程序(不在行)同等待
- 工作铬/Firefox/边(如1/30/2018)
更多 MDN
您可以使用的承诺,使AJAX调用顺序。使用数组压入和弹出承诺方法,顺序AJAX调用将容易得多。
var promises = [Promise.resolve()];
function methodThatReturnsAPromise(id) {
return new Promise((resolve, reject) => {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/'+id,
dataType:'json',
success: function(data)
{
console.log("Ajax Request Id"+id);
console.log(data);
resolve();
}
});
});
}
function pushPromise(id)
{
promises.push(promises.pop().then(function(){
return methodThatReturnsAPromise(id)}));
}
pushPromise(1);
pushPromise(3);
pushPromise(2);
如何使用Node.js的事件?
var EventEmitter = require('events').EventEmitter;
var eventEmitter = new EventEmitter();
var $ = require('jquery');
var doSomething = function (responseData) {
var nextRequestData = {};
// do something with responseData
return nextRequestData;
};
// ajax requests
var request1 = $.ajax;
var request2 = $.ajax;
var requests = [request1, request2];
eventEmitter.on('next', function (i, requestData) {
requests[i](requestData).then(
function (responseData) {
console.log(i, 'request completed');
if (i+1 < requests.length) {
var nextRequestData = doSomething(responseData);
eventEmitter.emit('next', i+1, nextRequestData);
}
else {
console.log('completed all requests');
}
},
function () {
console.log(i, 'request failed');
}
);
});
var data = {
//data to send with request 1
};
eventEmitter.emit('next', 0, data);
顺序!=同步,我想一个异步和连续溶液
同步执行通常是指“使用相同的时钟”,而顺序执行的意思是“在顺序或次序以下”。
有关特定使用情况下,我认为这两个条件必须满足,如异步执行意味着非顺序结果的可能性。