55

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

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Zen
  • 5,065
  • 8
  • 29
  • 49
  • 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`). – nils May 21 '16 at 13:29
  • This seems to be a bug caused by typescript, because the console actually outputs 10 'hello' when I log `bar`. – Zen May 21 '16 at 15:54

2 Answers2

102

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:

Westy92
  • 19,087
  • 4
  • 72
  • 54
  • 28
    @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. – Westy92 Aug 03 '17 at 19:35
  • 1
    `Promise.allSettled` is probably also worth mentioning in this context. Documentation [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled) – Robert Sep 17 '21 at 14:08
2

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

Zoe
  • 27,060
  • 21
  • 118
  • 148
null1941
  • 972
  • 8
  • 20