【问题标题】:How to await multiple calls of the same function with different params in Javascript如何在Javascript中等待具有不同参数的同一函数的多次调用
【发布时间】: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


【解决方案1】:

听起来你想要做的是首先迭代,但是需要多次调用getRecipes,并将返回的 Promise 存储在一个数组中。只有在您完成循环迭代、进行所有必需的调用并将它们推送到数组后,您才会将该数组传递给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();

【讨论】:

    【解决方案2】:

    尝试asyncawait 以获得干净的代码,如果我们指望.then,这种情况会变得复杂

    你的问题在这里Promise.all(ingredientList).then((result) =&gt; console.log('Done Waiting'));

    then 中的result 有你的价值观

    解决方案:

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

    希望你现在有一个清晰的想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-06
      • 2020-02-06
      • 2020-01-22
      • 2014-02-05
      • 2020-05-07
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多