简体   繁体   中英

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!

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM