我正在 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/