I have an array of strings in JavaScript. The array is defined like the following:
var myArray = [];
myArray.push('1');
myArray.push('2');
myArray.push('3');
I need to loop through the array and call a function that runs asynchronously. That 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'm trying to iterate through all of the items in my array and figure out how long it takes to run 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 finish before moving to the next item in the array. I know I need to use callbacks. However, I'm not sure how to structure my code that way. How do I do this?