Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

232
Views
Using array map on returned value from promise

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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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;
});
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!