Sequelize correctly execute multiple create + updates

I have a cron job that resets a list of items on a website and then inserts or updates records in the database. When I clear the page, I want to create entries for new ones that have not yet been created, otherwise update existing ones. I am currently doing something like this:

// pretend there is a "Widget" model defined function createOrUpdateWidget(widgetConfig) { return Widget.find(widgetConfig.id) .then(function(widget) { if (widget === null) { return Widget.create(widgetConfig); } else { widget.updateAttributes(widgetConfig); } }); } function createOrUpdateWidgets(widgetConfigObjects) { var promises = []; widgetConfigObjects.forEach(function(widgetConfig) { promises.push(createOrUpdateWidget(widgetConfig)); }); return Sequelize.Promise.all(promises); } createOrUpdateWidgets([...]) .done(function() { console.log('Done!'); }); 

Everything seems to be working fine, but I'm not sure if I am doing this β€œright” or not. Do all promises that perform interactions with the database need to be run alternately, or how do I define them normally? Is there a better way to do this?

+7
promise
source share
1 answer

What you are doing is pretty idiomatic and wonderful, the only opportunity for improvement is to use the fact that Sequelize uses Bluebird for promises, so you get .map for free, which allows you to convert:

 function createOrUpdateWidgets(widgetConfigObjects) { var promises = []; widgetConfigObjects.forEach(function(widgetConfig) { promises.push(createOrUpdateWidget(widgetConfig)); }); return Sequelize.Promise.all(promises); } 

IN:

 function createOrUpdateWidgets(widgetConfigObjects) { return Sequelize.Promise.map(widgetConfig, createOrUpdateWidget) } 

Other than this minor improvement, you are tying promises correctly and seem to be using it correctly.

+6
source share

All Articles