【问题标题】:Using array map on returned value from promise在 promise 的返回值上使用数组映射
【发布时间】:2022-01-15 00:49:09
【问题描述】:

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

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.all
  • 如果 Reddit.getComments 有某种形式的使用限制,您可能会发现 promise.all 可能会被阻止,如果是这样,您可能想改用 for of
  • @KrzysztofKrzeszewski 这似乎奏效了。谢谢!

标签: javascript redux react-redux


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 2019-09-28
    • 2017-01-19
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多