AJAX在数组循环中调用,只在上一次完成后调用next

AJAX call in array loop, call next only after previous complete

本文关键字:调用 next 上一次 数组 循环 AJAX      更新时间:2023-09-26

我有一个数组要上传数据,我希望它们一个接一个地发送到服务器。我想在发送下一个之前完成上一个。事实上,每次回复后,我都想决定是否发送下一个。

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();
}

您可以使用递归函数并在其中放入递归调用:

(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();
                 }); 
     }
})();