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?
source share