web-dev-qa-db-fra.com

Comment attendre une liste de promesses en JavaScript / TypeScript?

J'ai le code suivant, fileStatsPromises est de Promise<Stats>[], foo et bar sont Promise<Stats>[]. Quelle est la bonne façon de les attendre? Je veux obtenir <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: un exemple minimal.

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

24
Zen

C'est correct:

const bar = await Promise.all(promiseArray);

await Promise.all([...]) prend un tableau de promesses et retourne un tableau de résultats.

bar sera un tableau: ['hello', ..., 'hello']

Vous pouvez également déconstruire le tableau résultant:

const [bar1, ..., bar10] = await Promise.all(promiseArray);
console.log(bar1); // hello
console.log(bar7); // hello
52
Westy92

Veuillez utiliser Promise.all(). Veuillez vous référer à la documentation officielle https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

0
null1941