问题
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();
}
回答1:
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();
});
}
})();
来源:https://stackoverflow.com/questions/36626803/ajax-call-in-array-loop-call-next-only-after-previous-complete