【问题标题】:Async/Await NodeJS异步/等待 NodeJS
【发布时间】:2020-09-06 05:49:27
【问题描述】:

我正在使用 Node.js,但在使用 async/await 时遇到了一些问题。我的项目每天一次从多个端点重新获取数据,并通过调用一个广泛的重新获取函数来实现:

async function refetch() {
  await refetchOne();
  await refetchTwo();
  await refetchThree();
  await refetchFour();
  await refetchFive();
}

现在,我希望它按特定顺序重新获取(如上所述,1 -> 2 -> 3 -> 4 -> 5)。但是,有时无法保持顺序(即 refetchFive 被调用并在 Four 或 Three 完成之前完成。如何确保仅在前一个完成后才调用下一个 refetch 函数?

【问题讨论】:

  • 如果您的代码和其中的所有异步调用真的像您向我们展示的那样,那么您将无法得到:refetchFive gets called and finishes before Four or Three are finished。显示一些真实代码,以便我们确保您正确描述您的问题

标签: node.js asynchronous async-await


【解决方案1】:

串联运行 async/await 函数数组的最简单方法是使用 for...of。这将按顺序执行它们,一次一个,并等待每个解决。

const asyncA = async () => {
  return 'a'
}

const asyncB = async () => {
  return 'b'
}

const asyncC = async () => {
  return 'C'
}

const list = [asyncA, asyncB, asyncC]

for (const fn of list) {
  await fn() // call function to get returned Promise
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 2018-02-08
    • 2020-03-31
    • 2019-06-30
    • 2019-08-08
    • 1970-01-01
    • 2021-05-25
    • 2020-06-19
    相关资源
    最近更新 更多