Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda