I'm trying to get the following simplified code to finish and then move on synchronously:
factors.forEach(function(factor, index){
Factor.findOrCreate({function_name: factor}).exec(function(){
sails.log('success');
})
});
How do I do it?
So far I've tried:
- Putting lines 2-4 in a separate function and calling that from inside the loop
- Using the async.js async.series() call
But while it will execute the calls (print 'success'), it'll find or create a Factor in the DB very infrequently, so it has something to do with the asynchronous nature of the code.
Using promises to wait until all findOrCreate() calls return, then continuing
var promises = []; factors.forEach(function(factor, index){ promises.push(Factor.findOrCreate({function_name: factor})); }); Q.all(promises).then(function(){ sails.log('success'); });
I've tried a few versions of this one, but I still can't get it to print 'success' - This seems like the right way to do it, but I'm not quite sure what's wrong.