Search code examples
javascripttypescriptasync-awaitecmascript-next

How to await multiple Promises?


I have following code, fileStatsPromises is of Promise<Stats>[], both foo and bar are Promise<Stats>[]. What is the correct way to await them? I want to get <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);

EDIT: a minimal example.

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);
})();

Screenshot


Solution

  • This is correct:

    const bar = await Promise.all(promiseArray);
    

    await Promise.all([...]) takes an array of Promises and returns an array of results.

    bar will be an array: ['hello', ..., 'hello']

    You can also deconstruct the resulting array:

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

    There are a few similar functions you can use depending on your use case: