我有一个名为“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);
}
我一直在阅读有关回调和 promise 的信息,但无论我何时放置它们,该函数似乎都是异步触发的。任何帮助表示赞赏!
最佳答案
将使用 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])
关于javascript - 如何使用循环多次(同步)调用同一个异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33150987/