sakeferret
sakeferret

Reputation: 315

how can i call the same asynchronous function multiple times (synchronously) using a loop?

I have a an array called "products" that varies on each page load. I then need to call a function "addProduct()" for as many times as "products" is long, and use an altered value of each index inside that function. The function is long a complex and uses asynchronous calls (like .get) How can I stop the for loop from going to the next iteration until addProduct() is finished executing?

 function addProduct(productVariable){

      // (...do some long and asynchronous things with productVariable...)
 }

 //products array can vary in length on each page load
 products = ["prod01","prod02","prod03","prod04","prod05",...];

 for (var i = 0; i < products.length; i++) {

      var productAlter = product[i];

      //(...do some things with productAlter, but wait 
      // until the previous loop's addProduct() function 
      // has completed successfully)

      addProduct(productAlter);
 }

I keep reading about callbacks and promises, but no matter when I put them, the function seems to fire asynchronously. Any help is appreciated!

Upvotes: 1

Views: 1019

Answers (1)

mohamed-ibrahim
mohamed-ibrahim

Reputation: 11137

Will make use of success callback for Ajax to call addNextProdut and if the index reach its max then it will stop.

function addProduct(productVariable){
  $.ajax({
   url: your_action_server_url,
   context: document.body,
   success: function(){
     addNextProduct()
   }
   })
 }

 function addNextProduct(){
    index++; 
    if(index < products.length)
      addProduct(products[index])
 } 

 products = ["prod01","prod02","prod03","prod04","prod05",...];
 index = 0;
 addProduct(products[index])

Upvotes: 4

Related Questions