在forEach里面做asynchronous调用

我想通过Node.js中的asynchronous函数迭代通过对象的数组,并添加这些对象内的一些东西。

到目前为止我的代码如下所示:

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.each

 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}); }); 

当所有条目都被处理时,最后的callback将被调用。

既然你已经在使用承诺,最好不要把这个隐喻与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; }) ; }