繁体   English   中英

在forEach中进行异步调用

[英]make async call inside forEach

我试图通过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中实现这样的功能?

既然你已经在使用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;
        })
    ;
}

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

处理完所有条目后,将调用最终回调。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM