最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - make async call inside forEach - Stack Overflow

programmeradmin0浏览0评论

I am trying to iterate thru array of objects and add some stuff inside these objects using async function in Node.js.

So far my code looks like:

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

How can I achieve such a thing in JavaScript?

I am trying to iterate thru array of objects and add some stuff inside these objects using async function in Node.js.

So far my code looks like:

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

How can I achieve such a thing in JavaScript?

Share Improve this question edited Mar 21, 2015 at 4:26 user663031 asked Mar 21, 2015 at 3:21 LulzimLulzim 5474 gold badges9 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Since you are already using promises, better not to mix that metaphor with async. Instead, just wait for all the promises to finish:

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

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

The final callback will be called when all entries are processed.

发布评论

评论列表(0)

  1. 暂无评论