1

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 ?

jarlh
  • 42,561
  • 8
  • 45
  • 63
JAN
  • 21,236
  • 66
  • 181
  • 318
  • Does this answer your question? [Best way to call an asynchronous function within map?](https://stackoverflow.com/questions/33438158/best-way-to-call-an-asynchronous-function-within-map) – thomaux Sep 01 '21 at 07:55

1 Answers1

1

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));
thomaux
  • 19,133
  • 10
  • 76
  • 103
  • Thanks , but it gives a `(node:24384) UnhandledPromiseRejectionWarning: TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))` ..... it returns an object and not an array of promises – JAN Sep 01 '21 at 08:09
  • Are you sure the list of employees is an array? – thomaux Sep 01 '21 at 13:59