How to await multiple Promises?
Asked Answered
A

2

60

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

Ambidexterity answered 21/5, 2016 at 8:23 Comment(2)
Your code is pretty incomplete. Could you provide an example that can actually be run (including a definition of stat)? Apart from that, if fileStatsPromises is an array of Promises, you should be fine with your second option (bar).Nairn
This seems to be a bug caused by typescript, because the console actually outputs 10 'hello' when I log bar.Ambidexterity
S
106

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:

Stockmon answered 7/10, 2016 at 16:21 Comment(2)
@Everyone_Else the question asks for TypeScript as well. Plus this is valid JS (ES2017) and works in recent versions of Node.js 7 and 8. If you need an older version of JS, you can run your source through something like Babel.Stockmon
Promise.allSettled is probably also worth mentioning in this context. Documentation hereNigritude
P
2

Please use Promise.all(). Please refer the official documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Pocosin answered 24/2, 2019 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.