【发布时间】:2021-03-21 04:30:19
【问题描述】:
我正在为给定的 id 列表并行发出 https 请求:
const posts = await Promise.all(usersIds.map(userId => fetchUserPosts(userId)));
这会返回一个数组数组(因为 fetchUserPosts 返回一个列表):
[[{...post1Data}, {...post2Data}], [], [{...post3Data}], [{...post4Data}]]
我想要一个包含所有帖子的简单列表。
有什么想法吗?我想我必须使用 Promise.all 和 forEach 但这不起作用,因为我需要 Promise.all 参数的一系列承诺......
代码示例
const usersIds = [1, 2, 3, 4];
(async () => {
const posts = await Promise.all(usersIds.map(userId => fetchUserPost(userId)));
console.log(posts);
})();
function fetchUserPost(userId) {
return new Promise((resolve) => resolve([{ owner: userId }, { owner: userId } ]));
}
【问题讨论】:
-
可以分享一下
forEach的实现吗? -
你能发一个minimal working example吗? javascript中没有“列表”
-
@evolutionxbox developer.mozilla.org/es/docs/Web/JavaScript/Referencia/…
-
但是你的实现呢?
标签: javascript async-await es6-promise