问题
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!!
回答1:
Using Node 6.0, in built Promises can be used.
convertProductfields: function (articlesFromAurelia){
var allPromises = articlesFromAurelia
.map(post => new Promise((resolve, reject) => {
Categories.find({name: post.Categoria})
.then((category) => resolve(category))
.fail((error) => reject(error))
}));
return Promise.all(allPromises);
}
And to use the above function,
convertProductfields(articlesFromAurelia)
.then(() =>{
//handle success
}).catch(() => {
//handle error
})
回答2:
Hope it helps you.
convertProductfields: function (articlesFromAurelia, callback){
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 callback(null); //incase of error, return null
sails.log.debug('articlesFromAureliaModified ' , articlesFromAurelia);
return callback(articlesFromAurelia); //return updated articles
});
}
来源:https://stackoverflow.com/questions/41567117/using-async-inside-another-function