对promise返回的值使用数组映射



我正在Redux中编写一个异步thunk来获取Reddit帖子,然后通过返回的数组进行映射以获取每个帖子的注释,并将它们添加到新对象中。

export const fetchPosts = createAsyncThunk("posts/fetchPosts", async ({ name, filter }) => {
const data = await Reddit.getPosts(name, filter).then(async (val) => {
const posts = await val.map(async (post) => {
const comments = await Reddit.getComments(post.subreddit, post.id).then(val => {
return val;
});

return { ...post, comments: comments };
});

return posts;
});
return data;
});

然而,当thunk在我的应用程序中运行时,会发生错误,因为promise在返回的data对象中仍然挂起。我该如何纠正?

在返回的数据对象上使用Promise.all()确保数组返回所有从Reddit获取的帖子及其注释。

export const fetchPosts = createAsyncThunk("posts/fetchPosts", async ({ name, filter }) => {
// Fetching posts from Reddit
const data = await Reddit.getPosts(name, filter).then(async (val) => {
// Mapping through posts array
const posts = await val.map(async (post) => {
// Fetching comments for each post
const comments = await Reddit.getComments(post.subreddit, post.id).then(val => {
return val;
});

// Adding comments to each post object
return { ...post, comments: comments };
});

return posts;
});
// Awaiting fulfillment of promises for each post in array
const processed = Promise.all(data).then(val => {
return val;
});

// Returning processed data with comments included
return processed;
});

相关内容

  • 没有找到相关文章

最新更新