所以我有 sails 应用程序和一些帮助服务,可以更轻松地创建和获取复杂的模型。 其中之一是
getMerits: function(profileId, limit){
return async.waterfall([
function(callback){
Merit.find({employeeProfile: profileId}).then(function(merits){
callback(null, merits);
});
},
function(merits, callback){
async.forEach(merits, function(item, loop_callback){
MeritIndex.findOne({id: item.index}).then(function(meritIndex){
merits[merits.indexOf(item)].index = meritIndex;
loop_callback();
});
}, function(err, results){
callback(null, merits);
});
}
], function(err, results){
return results;
});
}
问题是当我尝试调用此函数来获取结果(插入了优点索引的优点列表。)时,我无法找出从异步 waterfall 返回结果的正确方法:
async.forEach(profiles, function(item, loop_callback){
MeritService.getMerits(item.id, 5).exec(function(err, merits){
console.log(merits)
profiles[profiles.indexOf(item)].merits = merits;
loop_callback();
});
// MeritService.getMerits(item.id, 5).exec(function(m){
// console.log(m)
// profiles[profiles.indexOf(item)].merits = m;
// loop_callback();
// });
}, function(err){
console.log("PROFILES" + JSON.stringify(profiles))
});
这里打印的优点结果是未定义的。有没有办法将异步 waterfall 视为 promise 并使用 then 而不是 exec?
最佳答案
您不需要使用async.waterfall
,因为您已经有了 promise , promise 链 - 因此为该逻辑添加另一个库是多余的。 Waterline 使用 Bluebird Promise,它已经提供了便捷的方法。
你的 getMerits 可以写成:
getMerits: function(profileId, limit){
var merits = Merit.find({employeeProfile: profileId});
var items = merits.map(function(item) {
return MeritIndex.findOne({id: item.index }).then(function(meritIndex) {
item.index = meritIndex;
});
});
return items.return(merits); // wait for items to be done, and return the merits
}
附注 如果您使用 Node 4+,请告诉我,因为它变得更加简单。
关于node.js - Nodejs 混合了异步函数和 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33089977/