Amarjit Singh
Amarjit Singh

Reputation: 2154

nodejs bulk update without compromising the performance

I have a node application with MySQL as DB. I on my way to making an endpoint that will update multiple rows with different data for each. Also, I am using sequelize as ORM.

Now I know I can update a row like

model.update(data).then(()=>{res.end('Row Updated')});

Now my question is where should I call update method for second model. ie in the cb function passed to then() or after the update.model method

I mean which of the following would be a best practice.

models1.update(data1).then(()=>{console.log('Row 1 Updated')});
model2.update(data2).then(()=>{console.log('Row 2 Updated')});

                      **OR**

model1.update(data1).then(()=>{
    model2.update(data2).then(()=>{console.log('All the rows have been updated')})
});

Upvotes: 3

Views: 460

Answers (1)

Estus Flask
Estus Flask

Reputation: 223259

Neither of the above are correct because promises aren't chained properly. This impedes proper control flow and error handling.

If queries are independent, they could be performed in parallel:

Promise.all([
  model1.update(data1),
  model2.update(data2)
])
.then(() => {
  console.log('All the rows have been updated');
});

Upvotes: 3

Related Questions