如何等待 JavaScript/TypeScript 中的 Promise 列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37360567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I await a list of Promises in JavaScript/TypeScript?
提问by Zen
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>[]
.
我有以下代码,fileStatsPromises
is of Promise<Stats>[]
, bothfoo
和bar
are Promise<Stats>[]
。等待他们的正确方法是什么?我想得到<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);
})();
回答by Westy92
This is correct:
这是对的:
const bar = await Promise.all(promiseArray);
await Promise.all([...])
takes an array of Promises and returns an array of results.
await Promise.all([...])
接受一组 Promise 并返回一组结果。
bar
will be an array: ['hello', ..., 'hello']
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
回答by null1941
Please use Promise.all()
.
Please refer the official documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
请使用Promise.all()
。请参考官方文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
回答by User Cybermerlin
I'm not sure what you mean, but maybe
bar.then(function(){ alert('complete') })
我不确定你的意思,但也许
bar.then(function(){ alert('complete') })