0

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
  • AJAX is asynchronous, and you should use it asynchronously. If you want to maintain some processing order, you shouldn't fight with AJAX to do so, but rather implement that logic server-side and send the whole array in one request... Commented Apr 14, 2016 at 14:58

1 Answer 1

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();
                 }); 
     }
})();
Sign up to request clarification or add additional context in comments.

2 Comments

but how would it ensure, it fires next before completing previous one
It will execute the function when promise is resolved. second call to loop will always be executed when first promise is resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.