make async call inside forEach

我怕爱的太早我们不能终老 提交于 2019-12-01 07:15:23

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.

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