【问题标题】:how can i call the same asynchronous function multiple times (synchronously) using a loop?如何使用循环多次(同步)调用相同的异步函数?
【发布时间】:2015-10-15 14:19:25
【问题描述】:

我有一个名为“products”的数组,该数组在每次页面加载时都会有所不同。然后,我需要调用函数“addProduct()”的次数与“products”一样多,并使用该函数内每个索引的更改值。该函数很复杂并且使用异步调用(如 .get)在 addProduct() 执行完成之前,如何阻止 for 循环进入下一次迭代?

 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);
 }

我一直在阅读有关回调和承诺的信息,但无论何时放置它们,该函数似乎都是异步触发的。任何帮助表示赞赏!

【问题讨论】:

  • 使用递归函数,在完成异步操作后使用全局计数器调用自身以迭代所有产品。我在用手机,所以写代码太难了。
  • 试试看Promises
  • @AlvaroFlañoLarrondo 感谢 Alvaro,这可能是我想要的。当您有时间记下一些笔记时,将不胜感激...谢谢!
  • 我的想法几乎就是@mohamed-ibrahim 的回答。
  • @AlvaroFlañoLarrondo 好的,非常感谢!

标签: javascript for-loop asynchronous callback


【解决方案1】:

将利用成功回调让 Ajax 调用addNextProdut,如果索引达到最大值,它将停止。

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

【讨论】:

  • 谢谢@mohamed-ibrahim。如果您不介意澄清这种情况.. test.html 会包含什么?
  • 对不起,这是一个例子,你应该用你的网址替换它
猜你喜欢
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2013-07-12
  • 1970-01-01
  • 2020-10-13
  • 2012-02-25
  • 2020-12-20
相关资源
最近更新 更多