Mario S
Mario S

Reputation: 1984

Detect all XMLHttpRequest calls are completed

I have Javascript code that uploads files to a server. Each upload is done using a XMLHttpRequest object.

xhr = new XMLHttpRequest();

//...

xhr.open('POST', 'https://<bucket>.s3.amazonaws.com/', true);
xhr.send(fd);

The upload in parallel works fine. The problem is that I need to detect when all of them have finished, because I have to do a final submit, but only if all the uploads are completed.

My first try was save all the xhr objects in an array but I didn't know what to do with that :-(

var arrayxhr = [];

//...

//A loop {
    xhr = new XMLHttpRequest();
    arrayxhr.push(xhr);

    xhr.open('POST', 'https://<bucket>.s3.amazonaws.com/', true);
    xhr.send(fd);
//}

//And now?

I found this jQuery function https://api.jquery.com/ajaxcomplete/, but the same, I don't really know how to use it.

Can you help me please?

TIA,

Upvotes: 0

Views: 7806

Answers (2)

Mario S
Mario S

Reputation: 1984

Well, this is not exactly the answer to my question (detect that the asynchronous calls are completed), but this answer works for me. I copy here just in case it helps someone else:

2: On the client-side, create a stack of files to upload and upload one at a time, calling the next one on the "Complete" callback of the previous.

https://stackoverflow.com/a/15557631/1893936

Upvotes: 0

Alex
Alex

Reputation: 11245

If you can use jQuery you can use jQuery AJAX Deferred interface/methods and $.when method. $.ajax/$.post/$.get and other jQuery AJAX methods always return jQuery Deferred object:

$.when($.get('someUrl'), $.get('anotherUrl')).then(function () {
    //all request complete
});

In native javascript you can use native Promise or any promise library:

Also good article about Promises - http://www.html5rocks.com/en/tutorials/es6/promises/.

Native Promise with XMLHttpRequest example:

function doAjaxRequest(method, url, data){
  var promise = new Promise();
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);

  // Register the event handler
  xhr.onload = function(){
    if(xhr.status === 200){
      promise.resolve("Done");
    } else{
      promise.reject("Failed");
    }
  }; 

  data = data || {};

  xhr.send(data);

  return promise;
}

Promise.all(doAjaxRequest('post', 'someUrl'), doAjaxRequest('post', 'anotherUrl')).then(function (values) {
    //all request complete
});

Upvotes: 4

Related Questions