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);
})();
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.
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.
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.
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.
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
Please use Promise.all()
.
Please refer the official documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With