[英]How to await multiple calls of the same function with different params in Javascript
如何在 Javascript 中等待具有不同參數的相同 function 的多個調用?
我知道Promise.All([func1, func2, func 3...])
但是我本質上是從“for循環”調用 function getRecipes(ingredients)
,每次將不同的“成分”傳遞到getRecipes()
. 我無法將[getRecipes,getRecipes,getRecipes]
數組傳遞給Promise.All()
因為我每次都需要傳遞不同的參數。
那么,我應該如何等待所有getRecipes()
結果返回,然后在它們全部完成后進行處理? 我不知道getRecipes
請求的數量,因為它是基於“for 循環”動態調用的。
示例代碼:`
const newAnnotatedList = []
const ingredientList = []
for(var i = 0; i < listOfPictures.length; i++) {
const ingredients = runClarifai(listOfPictures[i].uri)
ingredientList.push(ingredients)
}
console.log('Starting to wait')
Promise.all(ingredientList).then((result) => console.log('Done Waiting'));
for(var i = 0; i < listOfPictures.length; i++) {
const ingredients = ingredientList[i]
// ingredientList.push(ingredients)
newAnnotatedList.push({id:listOfPictures[i].id ,uri:listOfPictures[i].uri, ingredients: ingredients})
}
`
例如,當我console.log(ingredientsList[0])
時,我沒有返回 promise 的值(成分字符串數組),而是:
Promise {
"_40": 1,
"_55": null,
"_65": 0,
"_72": Handler {
"onFulfilled": [Function anonymous],
"onRejected": [Function anonymous],
"promise": Promise {
"_40": 0,
"_55": null,
"_65": 0,
"_72": null,
},
},
}
聽起來您想要做的是首先迭代,但是需要多次調用getRecipes
,然后將返回的 Promises 存儲在一個數組中。 只有在完成循環迭代、進行所有必需的調用並將它們推送到數組后,您才會將該數組傳遞給Promise.all()
:
function getRecipes(i) { return new Promise((resolve, reject) => { const timeout = Math.floor(Math.random() * 1500); setTimeout(() => resolve(i), timeout); }); } function callGetRecipesLoop() { const randNum = Math.floor(Math.random() * 10); console.log(randNum + ' results expected'); const promisesArray = []; for (let i = 0; i < randNum; i++) { promisesArray.push(getRecipes(i)); } Promise.all(promisesArray).then((result) => console.log(result)); } callGetRecipesLoop();
嘗試async
await
以獲得干凈的代碼,如果我們指望.then
,這種情況會變得復雜
你的問題在這里Promise.all(ingredientList).then((result) => console.log('Done Waiting'));
result
then
有你的價值觀
解決方案:
const test = async() => {
const arrayOfResult = await Promise.all(ingredientsList.map(ingredient => getrecipies(ingredient)))
console.log(arrayOfResult) // [promise1_result, promise2_result, ...]
}
test()
希望你現在有清晰的想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.