【问题标题】:How to use async await inside Lodash _.times function?如何在 Lodash _.times 函数中使用异步等待?
【发布时间】:2019-10-26 18:12:13
【问题描述】:

我想调用一个异步函数 n 次,每次只有在前一个解决后才调用。

这是有效的代码:

async startGame() {
  for (let i = 0; i < this.totalNumberOfSets; i++) {
  await this.startSet();
  }
}

我想将其转换为 Lodash 函数_.times

我尝试使用这个答案:Lodash: is it possible to use map with async functions?

这样:

async startGame() {
  await Promise.all(_.times(this.totalNumberOfSets, async () => {
    await this.startSet()
  }))
};

但所有函数都立即调用了四次,无需等待解析。

也试过这个:

  async startGame() {
   let resArray = [];
   await Promise.all(_.times(this.totalNumberOfSets, async () =>{
     let res = await this.startSet()
     resArray.push(res);
    }
  ))
 };

但它也没有按预期工作。

【问题讨论】:

标签: javascript async-await lodash


【解决方案1】:

尝试使用这个包,它支持 lodash 中的 async/await https://www.npmjs.com/package/async-dash

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 1970-01-01
    • 2018-09-29
    • 2023-04-03
    • 2023-01-27
    • 2018-04-23
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多