'ER_LOCK_DEADLOCK: Deadlock found when trying to get lock; try restarting transaction

I've been trying to bulk delete existing data from a table and bulk insert fresh data(probably around 1000 records at a time) from different sources into a table and I am getting this error "ER_LOCK_DEADLOCK: Deadlock found when trying to get lock; try restarting transaction".

Can anyone help me how to resolve the deadlock error?

Here is the code.

async function updateAllAccounts(request, response) {
    var query = 'SELECT admin, token FROM user WHERE process_background_flag = true'; // the query fetches around 30 records
    try {
        var rows = await runSqlFunc(request, query);
        var res = await processAccount(request, response, rows);
        return res;
    } catch (ex) {
        console.log('error = ' + ex);
    }
}

function processAccount(request, response, rows) {
    var funcArr = rows.map((row) => {
        return fetchAccount(request, response, row.admin);
    });
    //for eg: funcArr = [fetchAccount(request, response, admin1),fetchAccount(request, response, admin2), fetchAccount(request, response, admin3)......fetchAccount(request, response, admin30)]
    return Promise.allSettled(funcArr); // this will execute fetchAccount() parallelly for 30 admins 
}

async fetchAccount(req, res, adminVal) {
    try {
        //api request to third party resource
        var getResp; //this will have the API response from the 3 rd party resource

        var query = 'delete from teachers where admin = adminVal '; // this will delete all the teacher record under the specified admin
        await runSqlFunc(req, query);
        var valsArr = getResp.map(e => [adminVal,e.id, e.name, e.email, e.org, e.sis_id]);//valsArr is an array of 1000 arrays.
        query = 'insert into teacher (admin,id, name, email, org, sis_id) values 
                (valsArr)'; //this will insert all 1000 record into teacher table at a time
        await runSqlFunc(req, query);
    } catch (ex) {
        return ex;
    }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source