我正在尝试迭代对象数组并使用 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 中实现这样的事情呢?
既然您已经在使用承诺,最好不要将该隐喻与async
。相反,只需等待所有承诺完成即可:
Promise.all(channel.map(getData))
.then(function() { console.log("Done"); });
where getData
is:
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;
})
;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)