【问题标题】:handle mutilple async call and wait for all to complete before updating state在更新状态之前处理多个异步调用并等待全部完成
【发布时间】: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


【解决方案1】:

使用Promise.all()

const promises = [];

// 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 !!
    const promise = 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}`)
    })

  promises.push(promise);
})


Promise.all(promises).then(() => {
   // All finished
});

【讨论】:

    猜你喜欢
    • 2011-02-15
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 2014-09-20
    • 2021-06-18
    相关资源
    最近更新 更多