简体   繁体   English

Sequelize.update() 拒绝在异步函数中工作并且不更新/不等待

[英]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.每当我尝试更新使用多行(甚至只是单行) .update()的方法Sequelize ,代码永远不会等待并在.update()并没有真正更新。

Is it even working or am I doing something wrong ?它甚至工作还是我做错了什么?

Array.map is not async aware. Array.map不知道异步。 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.如果您想实现这种设置,您需要使用Array.map将您的列表转换为承诺,然后使用Promise.all等待所有承诺并返回结果数组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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