本文介绍了如何等待JavaScript/TypeScript中的Promises列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,fileStatsPromises
是Promise<Stats>[]
,foo
和bar
都是Promise<Stats>[]
.等待他们的正确方法是什么?我想得到<Stats>[]
.
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);
一个最小的例子.
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);
})();
推荐答案
这是正确的:
const bar = await Promise.all(promiseArray);
await Promise.all([...])
接受一个Promises数组并返回一个结果数组.
await Promise.all([...])
takes an array of Promises and returns an array of results.
bar
将是一个数组:['hello', ..., 'hello']
您还可以解构所得数组:
You can also deconstruct the resulting array:
const [bar1, ..., bar10] = await Promise.all(promiseArray);
console.log(bar1); // hello
console.log(bar7); // hello
这篇关于如何等待JavaScript/TypeScript中的Promises列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!