![](/img/trans.png)
[英]How to throttle a for in Javascript loop that has an async await api call inside?
[英]How to make an API call inside for loop, withour using async await
在 promise 中有一個 for 循環。 如何在不使用異步等待的情況下從 getData API 獲得響應。 getData 內部使用的參數來自 for 循環。
var res = EService.webApi.get.GetActiveData(formModel.project.EID);
res.then(
async function (result) {
//success
var data = result.data;
var eList= data.BodyData;
var jList= [];
for (var i = 0; i < eList.length; i++) {
let entity = await getData(eList[i].EntityID);
if (eList[i].typeID !== 16) {
jList.push({
Name: eList[i].Name + " - " + e[i].typeName + " - " + entity.Name,
EID: eList[i].EntityID,
model: eList[i],
});
}
}
}
如果我理解您的要求,聽起來您想立即調用所有異步請求,但讓每個請求都等待其結果,而不是在每個等待前一個操作的情況下串行調用它們。 也許是這樣的:
for (var i = 0; i < eList.length; i++) {
(async (j) => {
// The rest of your logic, but using the passed `j` instead of `i`
})(i);
}
不等待匿名async
function,但在內部每次調用該 function 可以await
調用getData
以使用其結果。
雖然如果您想在之后使用jList
或任何其他結果/副作用做某事,那么您需要等待整個事情。 也許將所有承諾放入一個數組並等待該數組。 也許是這樣的:
let promises = [];
for (var i = 0; i < eList.length; i++) {
promises.push((async (j) => {
// The rest of your logic, but using the passed `j` instead of `i`
})(i));
}
Promise.all(promises).then(() => ...);
總體目標是所有操作並行運行,而不是像原始循環中那樣串行運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.