简体   繁体   English

如何在 Javascript 中等待具有不同参数的相同 function 的多个调用

[英]How to await multiple calls of the same function with different params in Javascript

How can I await multiple calls of the same function with different params in Javascript?如何在 Javascript 中等待具有不同参数的相同 function 的多个调用?

I am aware of Promise.All([func1, func2, func 3...]) however I am essentially calling a function getRecipes(ingredients) from a "for loop" with different 'ingredients' being passed into getRecipes() each time.我知道Promise.All([func1, func2, func 3...])但是我本质上是从“for循环”调用 function getRecipes(ingredients) ,每次将不同的“成分”传递到getRecipes() . I can't pass an array of [getRecipes,getRecipes,getRecipes] into Promise.All() because I need to pass different params every time.我无法将[getRecipes,getRecipes,getRecipes]数组传递给Promise.All()因为我每次都需要传递不同的参数。

So how should I go about waiting for all of the getRecipes() results to be returned and then processing once they are all completed?那么,我应该如何等待所有getRecipes()结果返回,然后在它们全部完成后进行处理? I don't know the number of getRecipes requests since its dynamically called based on the "for loop".我不知道getRecipes请求的数量,因为它是基于“for 循环”动态调用的。

Sample Code: `示例代码:`

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

When I console.log(ingredientsList[0]) for example, I'm not returned the value of the promise (the array of ingredient strings) but instead:例如,当我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,
    },
  },
}

Sounds like what you want to do is first iterate through however many calls to getRecipes are required, and store the returned Promises in an array.听起来您想要做的是首先迭代,但是需要多次调用getRecipes ,然后将返回的 Promises 存储在一个数组中。 Only once you have finished iterating through your loop, making all the required calls and pushing them to the array do you then pass that array to Promise.all() :只有在完成循环迭代、进行所有必需的调用并将它们推送到数组后,您才会将该数组传递给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();

Try async await for clean code, such scenarios gets compilcated if we are counting on .then尝试async await以获得干净的代码,如果我们指望.then ,这种情况会变得复杂

Your problem is here Promise.all(ingredientList).then((result) => console.log('Done Waiting'));你的问题在这里Promise.all(ingredientList).then((result) => console.log('Done Waiting'));

result in then has your values result then有你的价值观

Solution:解决方案:

const test = async() => {
const arrayOfResult = await Promise.all(ingredientsList.map(ingredient => getrecipies(ingredient)))
console.log(arrayOfResult) // [promise1_result, promise2_result, ...]
}
test()

Hope you now have clear idea.希望你现在有清晰的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM