TransWikia.com

handle mutilple async call and wait for all to complete before updating state

Stack Overflow Asked by usernameUnknown on November 24, 2021

I try to make multiple async calls. I need to wait for every call to complete before updating my component state.

Here is my commented code so far (I tried to be clear with comments) :

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 });
    }
};

Thanks for help!

One Answer

Using 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
});

Answered by Emre Koc on November 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP