JavaScript arrays with asynchronous functions

I have an array of strings in JavaScript. An array is defined as follows:

var myArray = []; myArray.push('1'); myArray.push('2'); myArray.push('3'); 

I need to go through an array and call a function that runs asynchronously. This function looks like this:

 function myAsyncFunction(id, callback) { $.ajax({ url: '/api/items', data: { 'id':id }, type: 'POST', dataType: 'text', success: function(result) { if (callback) { callback(); } }, error: function() { if (callback) { callback(); } } } 

I am trying to iterate all the elements in my array and figure out how long it will take to start all of them. I want to do something like this:

 var startTime = new Date(); for (var i=0; i<myArray.length; i++) { myAsyncFunction(myArray[i]); } var duration = new Date() - startTime; 

Obviously, the above does not work, because it does not wait for the ajax call to complete before moving to the next element of the array. I know that I need to use callbacks. However, I am not sure how to structure the code this way. How to do it?

+5
source share
3 answers

Use Promise and do something like this:

 var myArray = [1, 2, 3]; var promises = []; var startTime = new Date(); var duration; for (var i = 0, len = myArray.length; i < len; i++) { var def = $.Deferred(); promises.push(def); (function(i) { $.ajax({ url: '/api/items', data: { 'id':myArray[i] }, type: 'POST', dataType: 'text' }).done(function() { promises[i].resolve(); }); })(i); } $.when.apply($, promises).done(function() { duration = new Date() - startTime; console.log(duration); }); 

I have not tested, but I think that it can work well with some adaptation :)
I think that a solution using a counter may not work under certain conditions.

EDIT: it works http://jsfiddle.net/0u21jwxv/

+2
source

Keep track of how many calls you are going to make

 var callCount = myArray.length; 

Then in callbacks check if its last

 success: function(result) { callCount--; if(callCount == 0){ var duration = new Date() - startTime; } } 
+1
source

Try using counter for this purpose. When the counter value is 0 , find the duration .

 var startTime = new Date(); var counter = myArray.length; //COUNTER for (var i=0; i<myArray.length; i++) { myAsyncFunction(myArray[i],function(){//Here you use the callback counter--; if(counter == 0){ var duration = new Date() - startTime; } }); } 
+1
source

All Articles