【问题标题】:How to use promise.all with forEach in javascript? [duplicate]如何在javascript中使用promise.all和forEach? [复制]
【发布时间】: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 } ]));
 }

【问题讨论】:

标签: javascript async-await es6-promise


【解决方案1】:

等待后可以flat列表

let posts = await Promise.all(usersIds.map(userId => fetchUserPosts(userId)));
posts = posts.flat();

【讨论】:

  • 谢谢,这正是我需要的
猜你喜欢
  • 2021-07-17
  • 2018-08-29
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2011-09-09
  • 2016-12-24
  • 2015-10-03
  • 2020-04-24
相关资源
最近更新 更多