I am using node.js and async with sails.js framework. I am trying to create a function that perform some async DB operations on an array of data but I have problems figuring out a simple way to return the results of async to the parent function. Here's my code:
convertProductfields: function (articlesFromAurelia){
async.each(articlesFromAurelia, function (post, cb) {
Categories.find({name: post.Categoria})
.then(function(category){
post.cat_id = category[0].cat_id;
cb();
})
.fail(function(error){
cb(error);
})
}, function(error){
if(error) return res.negotiate(error);
sails.log.debug('articlesFromAureliaModified ' , articlesFromAurelia);
return articlesFromAurelia;
});
sails.log.debug('articlesFromAureliaNotModified ' , articlesFromAurelia);
return articlesFromAurelia;
}
The problem of course is the execution order of the code. My function has already returned when the results of Async operations are available.... so, how to make it work? Thanks!!