我试图通过Node.js中的异步函数迭代通过对象数组并在这些对象中添加一些东西。
到目前为止,我的代码如下:
var channel = channels.related('channels');
channel.forEach(function (entry) {
knex('albums')
.select(knex.raw('count(id) as album_count'))
.where('channel_id', entry.id)
.then(function (terms) {
var count = terms[0].album_count;
entry.attributes["totalAlbums"] = count;
});
});
//console.log("I want this to be printed once the foreach is finished");
//res.json({error: false, status: 200, data: channel});
如何在JavaScript中实现这样的功能?
答案 0 :(得分:7)
由于您已经在使用promises,因此最好不要将该隐喻与async
混合使用。相反,只需等待所有承诺完成:
Promise.all(channel.map(getData))
.then(function() { console.log("Done"); });
其中getData
是:
function getData(entry) {
return knex('albums')
.select(knex.raw('count(id) as album_count'))
.where('channel_id', entry.id)
.then(function (terms) {
var count = terms[0].album_count;
entry.attributes["totalAlbums"] = count;
})
;
}
答案 1 :(得分:1)
async.each(channel, function(entry, next) {
knex('albums')
.select(knex.raw('count(id) as album_count'))
.where('channel_id', entry.id)
.then(function (terms) {
var count = terms[0].album_count;
entry.attributes["totalAlbums"] = count;
next();
});
}, function(err) {
console.log("I want this to be printed once the foreach is finished");
res.json({error: false, status: 200, data: channel});
});
处理完所有条目后,将调用最终回调。