I'm writing an async thunk in Redux to fetch Reddit posts, then map through the returned array to fetch each post's comments and add them to the new object.
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;
});
However, when the thunk is run in my app, an error occurs because the promises are still pending in the returned data object. How can I rectify this?
Using Promise.all() on the returned data object ensured the array came back with all the fetched posts and their comments from Reddit as outlined.
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;
});