如何在 javascript 中将 promise.all 与 forEach 一起使用?
How to use promise.all with forEach in javascript?
我正在为给定的 ID 列表并行发出 https 请求:
const posts = await Promise.all(usersIds.map(userId => fetchUserPosts(userId)));
这个returns我是一个数组的数组(因为fetchUserPostsreturns一个列表):
[[{...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 } ]));
}
等待之后你可以flat列表
let posts = await Promise.all(usersIds.map(userId => fetchUserPosts(userId)));
posts = posts.flat();
我正在为给定的 ID 列表并行发出 https 请求:
const posts = await Promise.all(usersIds.map(userId => fetchUserPosts(userId)));
这个returns我是一个数组的数组(因为fetchUserPostsreturns一个列表):
[[{...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 } ]));
}
等待之后你可以flat列表
let posts = await Promise.all(usersIds.map(userId => fetchUserPosts(userId)));
posts = posts.flat();