在 promise 的返回值上使用数组映射

Using array map on returned value from promise

我正在 Redux 中编写一个异步 thunk 来获取 Reddit posts,然后映射返回的数组以获取每个 post 的评论并将它们添加到新对象中。

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;
});

但是,当 thunk 在我的应用程序中 运行 时,会发生错误,因为返回的 data 对象中的 promise 仍未决。我该如何纠正?

在返回的数据对象上使用 Promise.all() 确保数组返回所有从 Reddit 获取的帖子及其评论,如前所述。

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;
});