Estoy escribiendo un thunk asíncrono en Redux para obtener publicaciones de Reddit, luego mapeo a través de la matriz devuelta para obtener los comentarios de cada publicación y agregarlos al nuevo objeto.
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; }); Sin embargo, cuando se ejecuta el procesador en mi aplicación, se produce un error porque las promesas aún están pendientes en el objeto data devuelto. ¿Cómo puedo rectificar esto?
El uso Promise.all() en el objeto de datos devuelto aseguró que la matriz regresara con todas las publicaciones recuperadas y sus comentarios de Reddit como se describe.
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; });