Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I await a list of Promises in JavaScript/TypeScript?

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

like image 682
Zen Avatar asked May 21 '16 08:05

Zen


People also ask

How do you wait for a promise in TypeScript?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

How do you resolve an array of promises?

all() The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.

Does await wait for all promises?

The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result.

Can you await a promise JavaScript?

The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.


2 Answers

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
like image 149
Westy92 Avatar answered Nov 07 '22 13:11

Westy92


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

like image 30
null1941 Avatar answered Nov 07 '22 11:11

null1941