数组循环中的AJAX调用,仅在上一个完成后才调用下一个 [英] AJAX call in array loop, call next only after previous complete
本文介绍了数组循环中的AJAX调用,仅在上一个完成后才调用下一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组来上传数据,并且我希望它们被一一发送到服务器. 我要先完成上一个,然后再发送下一个. 实际上,在每个响应之后,我都想决定是否发送下一个.
I have an array to upload data and I want them to send to server one by one. I want the previous one to complete before I send next one. Actually, after each response I want to decide whether to send next one or not.
while (packetCount < bulkUploadPackets.length) {
d = d.then(save(bulkUploadPackets[packetCount]))
.then(function(uploadResponse) {
//I want to come here after first call complete
//before second call is fired and so on
packetCount++;
});
}
save: function(modelToSave) {
var defer = $.Deferred();
var self = this;
this.model = modelToSave;
Backbone.sync('create', this, {
success: function(data, textStatus, jqXHR) {
console.log("success" + data);
defer.resolve(data);
},
error: function(response) {
defer.reject(errorObj);
}
});
return defer.promise();
}
推荐答案
您可以使用递归函数,然后将递归调用放在其中:
You can use recursive function and put recursive call inside then:
(function loop() {
if (packetCount<bulkUploadPackets.length) {
d = d.then(save(bulkUploadPackets[packetCount]))
.then(function(uploadResponse){
//I want to come here after first call complete before second call is fired and so on
packetCount++;
loop();
});
}
})();
这篇关于数组循环中的AJAX调用,仅在上一个完成后才调用下一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文