Sequelize Transaction Bulk Update followed by Bulk Create

10,603

I believe you're just after promise chaining with then? The first line should return a promise - so just call then on the result:

return sequelize.transaction(function(t){
  return sequelize.Promise.each(arrToUpdate, function(itemToUpdate){
    model.update(itemToUpdate, { transaction: t })
  }).then((updateResult) => {
    return model.bulkCreate(itemsArray, { transaction: t })
  }, (err) => {
    // if update throws an error, handle it here.
  }); 
});

Note: now your function will return a promise, so whatever calls your function will have to use then to get a handle on the result.

Share:
10,603

Related videos on Youtube

Chua Bing Quan
Author by

Chua Bing Quan

Updated on July 02, 2022

Comments

  • Chua Bing Quan
    Chua Bing Quan almost 2 years

    I am working with Sequelize transaction and would like to know how to do a bulk update before sequentially doing a bulk create.

    My current code is something like this:

    return sequelize.transaction(function(t){
      return sequelize.Promise.each(arrToUpdate, function(itemToUpdate){
        model.update(itemToUpdate, { transaction: t })
      }); 
      //How to do a sequential bulk create after the bulk update is successful in sequelize
      //transaction?
      //Bulk Create code would be return model.bulkCreate(itemsArray, { transaction: t })
    });

  • Chua Bing Quan
    Chua Bing Quan almost 7 years
    Thank you, I did not think of that! Was too caught up on the return model.update() inside the loop.