How do I await a list of Promises in JavaScript/Ty

2020-02-11 17:37发布

问题:

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

回答1:

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


回答2:

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



回答3:

I'm not sure what you mean, but maybe bar.then(function(){ alert('complete') })