如何等待 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:30:38  来源:igfitidea点击:

How do I await a list of Promises in JavaScript/TypeScript?

javascripttypescriptasync-awaitecmascript-next

提问by Zen

I have following code, fileStatsPromisesis of Promise<Stats>[], both fooand barare Promise<Stats>[]. What is the correct way to await them? I want to get <Stats>[].

我有以下代码,fileStatsPromisesis of Promise<Stats>[], bothfoobarare 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);
})();

Screenshot

截屏

回答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 并返回一组结果。

barwill 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

回答by User Cybermerlin

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

我不确定你的意思,但也许 bar.then(function(){ alert('complete') })