javascript - 如何知道异步调用是否完成? (黑客新闻评论)

标签 javascript reactjs rest promise

我正在 React/Redux 上构建一个 hackernews 克隆。

在组件内部,Item.js 我调用 this.props.fetchItem(this.props.match.params.id);

这是 fetchItem 操作创建者:

export const fetchItem = (id) => {
    return dispatch => {
        return axios.get(`${ROOT_API_URL}/item/${id}.json`)
            .then(response => {
                let story = response.data;
                let commentIds = response.data.kids; // Story kids
                var allComments = [];

                let fetchComments = commentIdArray => {
                    let promiseArray = [];

                    // 1. Create requests for each commentId
                    commentIdArray.forEach(commentId => {
                        promiseArray.push(axios.get(`${ROOT_API_URL}/item/${commentId}.json`));
                    })

                    // 2. Make requests to fetch all commentIds
                    axios.all(promiseArray)
                        .then(responseArray => {
                            responseArray.forEach(response => {
                                let comment = response.data;
                                allComments.push(comment);

                                if(comment.kids){
                                    fetchComments(comment.kids);
                                }else{
                                    return false;
                                }
                            })
                            console.log("allComments: ", allComments);
                        })
                        .catch(error => {
                            console.log("error promise.all: ", error);
                        })
                }

                fetchComments(commentIds)
            })
            .catch(error => {
                if(error.response.status === 401){
                    console.error("Unauthorized");
                }else{
                    console.error("Something went wrong!");
                }
            })
    }
}

基本上,它接收故事的 ID 并获取该故事的评论。这部分也有效。我将所有评论都放在扁平数组中。

问题就在这里。我必须在 fetchItem 中的某个位置调用 fetchItemSuccess ,这样我就可以将数据保存到 redux 中。虽然,我不知道有多少评论,并且我通过子评论递归地获取它们。

那么,我如何知道我已准备好所有评论,然后调用 fetchItemSuccess

一个故事:https://hacker-news.firebaseio.com/v0/item/8863.json?print=pretty

评论:https://hacker-news.firebaseio.com/v0/item/8952.json?print=pretty

最佳答案

想通了。

我只需要跟踪异步方法调用。所以,我添加了一个计数变量。如果计数为零,则分派(dispatch)一个操作。

export const fetchItem = (id) => {
    return dispatch => {
        return axios.get(`${ROOT_API_URL}/item/${id}.json`)
            .then(response => {
                let story = response.data;
                let commentIds = response.data.kids; // Story kids
                var allComments = [];
                var count = 0; // <=== New Line

                let fetchComments = (commentIdArray) => {
                    let promiseArray = [];
                    count++; // <=== New Line

                    // 1. Create requests for each commentId
                    commentIdArray.forEach(commentId => {
                        promiseArray.push(axios.get(`${ROOT_API_URL}/item/${commentId}.json`));
                    })
                    // 2. Make requests to fetch all commentIds
                    axios.all(promiseArray)
                        .then(responseArray => {
                            responseArray.forEach(response => {
                                let comment = response.data;
                                allComments.push(comment);

                                if(comment.kids){
                                    fetchComments(comment.kids);
                                }else{
                                    return false;
                                }
                            })
                            count--; // <=== New Line
                            if(count === 0){ // <=== New Line
                                dispatch( fetchItemSuccess(allComments) );
                            }
                        })
                        .catch(error => {
                            console.log("error promise.all: ", error);
                        })
                }

                fetchComments(commentIds);
            })
            .catch(error => {
                if(error.response.status === 401){
                    console.error("Unauthorized");
                }else{
                    console.error("Something went wrong!");
                }
            })
    }
}

关于javascript - 如何知道异步调用是否完成? (黑客新闻评论),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48144165/

相关文章:

javascript - 如何以 redux 形式传入动态表单名称?

javascript - 如果没有 React-hooks 并使用类组件而不是功能组件,这个 React 代码会是什么样子?(打开附加窗口的按钮)

Spring Boot Rest Controller 如何返回不同的 HTTP 状态码?

X3D 的 Scala 库

javascript - 如何在 MVC ScriptBundle 中将字符集设置为 .js 文件?

javascript - Angular2 - 使用 debounceTime 测试调用

javascript - 我不明白 Handlebars.js 自述文件中的这个 "block helpers"示例

javascript - 无法在不可变记录中正确设置此嵌套对象

javascript - Phaser - 显示图形对象 50 毫秒,并在同时按下一个或多个按键时销毁每个按键

http - HTTP 删除操作失败的 HTTP 响应代码是什么?