我有这个函数和内部 forEach
循环迭代槽项目......我想要实现的是呈现一些微调器(加载器)直到所有 http
请求完成,直到 forEach
循环完成。
我现在尝试的方式是,第一个和最后一个 console.log
立即触发,然后记录第二个 console.log
的次数与项目中的项目一样多大批。
当 forEach
迭代完成时,当所有 http
请求完成时,如何将状态更新为 loading: false
?
someHandler = () => {
// this.setState({ loading: false })
console.log( "Not loading" )
this.props.items.forEach(item => {
axios
.get(`.../${item}/`)
.then(res => {
this.setState(prevState => ({
item: [
...prevState.item,
{
name: res.data.name,
img: res.data.img
}
]
}));
this.props.newItem(this.state.item);
// this.setState({ loading: true })
console.log( "Loading" )
})
.catch(err => {
console.log(err);
// this.setState({ loading: false })
console.log( "Not loading" )
});
});
// this.setState({ loading: false })
console.log( "Not loading" )
};
最佳答案
您可以将 async/await
与 for...of
一起使用
您可以假设使用这种方法顺序执行。
someHandler = async () => {
console.log('Not loading'); // will execute before loop
this.setState({ loading: true }); // start loading
for (let item of this.props.items) {
const res = await axios.get(`.../${item}/`);
// ... do your logic with response
console.log('Loading');
}
console.log('Not loading'); // will execute after loop
this.setState({ loading: false }); // end loading
};
关于javascript - 检测包含 http 请求的 forEach 循环结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53723820/