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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-12 03:45:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!