【问题标题】:How to await multiple Promises?如何等待 JavaScript/TypeScript 中的 Promise 列表?
【发布时间】:2016-09-18 12:55:00
【问题描述】:

我有以下代码,fileStatsPromises 属于Promise<Stats>[]foobar 都是Promise<Stats>[]。等待他们的正确方法是什么?我想得到<Stats>[]

    const files = await readDir(currentDir);
    const fileStatsPromises = files.map(filename => path.join(currentDir, filename)).map(stat);

    const foo = await fileStatsPromises;
    const bar = await Promise.all(fileStatsPromises);

编辑:一个最小的例子。

function makePromise() {
    return Promise.resolve("hello");
}
const promiseArray = [];
// const promiseArray = [] as Promise<string>[];
for (let i = 0; i < 10; i++) {
    promiseArray.push(makePromise());
}

(async () => {
    const foo = await promiseArray;
    const bar = await Promise.all(promiseArray);
})();

【问题讨论】:

  • 您的代码非常不完整。您能否提供一个可以实际运行的示例(包括stat 的定义)?除此之外,如果fileStatsPromises 是一个 Promises 数组,那么您应该可以选择第二个选项 (bar)。
  • 这似乎是由打字稿引起的错误,因为当我登录bar时控制台实际上输出了10 'hello'。

标签: javascript typescript async-await ecmascript-next


【解决方案1】:

这是正确的:

const bar = await Promise.all(promiseArray);

await Promise.all([...]) 接受一个 Promises 数组并返回一个结果数组。

bar 将是一个数组:['hello', ..., 'hello']

你也可以解构生成的数组:

const [bar1, ..., bar10] = await Promise.all(promiseArray);
console.log(bar1); // hello
console.log(bar7); // hello

【讨论】:

  • @Everyone_Else 问题也要求使用 TypeScript。另外,这是有效的 JS (ES2017),适用于最新版本的 Node.js 7 和 8。如果您需要旧版本的 JS,您可以通过 Babel 之类的工具运行您的源代码。
  • Promise.allSettled 在这种情况下可能也值得一提。文档here
【解决方案2】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2018-04-17
    • 2021-09-23
    • 2020-03-04
    相关资源
    最近更新 更多