【发布时间】:2020-12-08 07:35:23
【问题描述】:
如何在 Javascript 中等待多次调用具有不同参数的同一函数?
我知道Promise.All([func1, func2, func 3 ...]) 但是我实际上是从“for 循环”调用函数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 {
"_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,getRecipes,getRecipes] 数组传递给 Promise.All()" --> 为什么不呢?如果
getRecipes返回一个 Promise,你可以随心所欲地调用它,并且每次都返回一个不同的 Promise -
自从我回答后你已经编辑了这个,你的代码看起来很像我的代码。您是否只是对为什么“开始”和“完成”控制台日志在结果中出现乱序感到困惑?因为这就是异步代码的工作方式——如果你想等待结果,你需要利用
async/await。 -
@AlexanderNied 啊,我认为这最初让我失望,但我接受了您的建议,将“完成”移动到 Promise.all().then() 函数。我仍然对为什么存储在 promise 数组中的值不是 promise 评估的值感到困惑?
标签: javascript asynchronous async-await