在forEach中进行异步调用

Lul*_*zim 4 javascript asynchronous node.js bookshelf.js

我试图通过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});
Run Code Online (Sandbox Code Playgroud)

我怎样才能在JavaScript中实现这样的功能?

小智 7

既然你已经在使用promises,最好不要混淆这个比喻async.相反,只需等待所有承诺完成:

Promise.all(channel.map(getData))
    .then(function() { console.log("Done"); });
Run Code Online (Sandbox Code Playgroud)

在哪里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;
        })
    ;
}
Run Code Online (Sandbox Code Playgroud)