0

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?

3
  • 3
    try Promise.all Commented Dec 10, 2021 at 9:54
  • If Reddit.getComments has some form of usage limits, you might find promise.all might get blocked, if so you might want to use for of instead. Commented Dec 10, 2021 at 10:04
  • @KrzysztofKrzeszewski That seems to have worked. Thanks! Commented Dec 10, 2021 at 10:06

1 Answer 1

1

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;
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.