简体   繁体   中英

Sequelize.update() refuses to work in async function and doesn't update / doesn't await

Consider the code:

const listOfEmployees = .... // get list of employees from god knows where ...
    
    
async function incrementHoursEmps(listOfEmployees) {
  listOfEmployees.map(async employeeId => {     
    const condition = { where : {employeeId} }; 
    const options = { multi: true };
    const values = { hoursWork: sequelize.literal('"hoursWork" + 1') };
    ModelEmployees.update(values, condition , options)
        .then(result => { 
            // ....
        })
        .catch(error => {
          console.log(error);
        });
    });
}
    
await incrementHoursEmps(listOfEmployees);

Whenever I try to update multiple rows (or even just a single row) using the .update() method of Sequelize , the code never awaits and the .update() doesn't really update.

Is it even working or am I doing something wrong ?

Array.map is not async aware. If you want to achieve this kind of setup you need to use Array.map to convert your list to promises, then use Promise.all to await on all promises and return an array of the results.

const listOfEmployees = .... // get list of employees from god knows where ...
    
async function incrementHoursEmps(listOfEmployees) {
    return listOfEmployees.map(employeeId => {
        const condition = { where: { employeeId } };
        const options = { multi: true };
        const values = { hoursWork: sequelize.literal('"hoursWork" + 1') };
        return ModelEmployees.update(values, condition, options);
    });
}

await Promise.all(incrementHoursEmps(listOfEmployees));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM