make async call inside forEach

让人想犯罪 __ 提交于 2019-12-01 04:30:28

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/29178868/make-async-call-inside-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!