make async call inside forEach

后端 未结 2 1019
误落风尘
误落风尘 2021-01-13 14:48

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          


        
相关标签:
2条回答
  • 2021-01-13 14:59

    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 讨论(0)
  • 2021-01-13 15:12

    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;
            })
        ;
    }
    
    0 讨论(0)
提交回复
热议问题