【发布时间】:2020-11-12 01:02:59
【问题描述】:
我尝试进行多个异步调用。在更新我的组件状态之前,我需要等待每个调用完成。
这是我到目前为止的注释代码(我试图用 cmets 清楚):
handleBatchDelete = () => {
const selected_id_to_delete = [58, 75.86, 103] // list of elements to delete by ids
const deleted_ids = [] // init empty list of for element that will successfully deleted
const failed_id = [] // init empty list for elements that will fail to delete
// loop through all ids to be deleted
selected_id_to_delete.map(id => {
// for each id call the DELETE api : Here is the async call !!
delete_item(id).then(res => {
// Success => add this id to the deleted_ids array
deleted_ids.push(id)
}).catch(error => {
// Failed => add this id to the failed_id array
failed_id.push(id)
console.log(`error when trying to delete this id : ${id}, message : ${error}`)
})
})
// Of course this will be executed before any async call...and I would like to wait for all call before executing these lines
if (deleted_ids.length > 0) {
// filter actual data from state with deleted items
const data = [...this.state.data].filter(
(elem) => !deleted_ids.find(id => elem.Id === id)
);
// finally set the state with the new data
this.setState({ data });
}
};
感谢您的帮助!
【问题讨论】:
-
不,我没有。我会试一试。感谢参考
标签: javascript arrays reactjs ajax