在forEach内部进行异步调用 [英] make async call inside forEach

查看:293
本文介绍了在forEach内部进行异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历对象数组,并使用Node.js中的异步功能在这些对象内添加一些东西.

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

如何在JavaScript中实现这种目标?

How can I achieve such a thing in JavaScript?

推荐答案

使用 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.

这篇关于在forEach内部进行异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆