Node.js - 使用async lib - async.foreach和object

时间:2012-04-30 20:19:54

标签: node.js loops object asynchronous node-async

我正在使用节点async lib - https://github.com/caolan/async#forEach,并希望迭代一个对象并打印出它的索引键。一旦完成,我想执行一个回调。

到目前为止,这是我所拥有的,但'iterating done'从未见过:

    async.forEach(Object.keys(dataObj), function (err, callback){ 
        console.log('*****');

    }, function() {
        console.log('iterating done');
    });  
  1. 为什么不调用最终函数?

  2. 如何打印对象索引键?

2 个答案:

答案 0 :(得分:120)

不会调用最终函数,因为async.forEach要求您为每个元素调用callback函数。

使用类似的东西:

async.forEach(Object.keys(dataObj), function (item, callback){ 
    console.log(item); // print the key

    // tell async that that particular element of the iterator is done
    callback(); 

}, function(err) {
    console.log('iterating done');
});  

答案 1 :(得分:0)

async.each是非常有用且功能强大的功能,由Async Lib提供。它有3个字段 1-收集/阵列 2-迭代 3,回调 集合是指对象的数组或集合,迭代是指每次迭代,回调是可选的。 如果我们给予回调,那么它将返回响应或说出您希望在前端显示的结果

将函数iteratee并行应用于coll中的每个项目。使用列表中的项目调用iteratee,并在完成时调用它。如果iteratee将错误传递给它的回调,则会立即调用主回调(对于每个函数)并显示错误。

注意,由于此函数并行地将iteratee应用于每个项目,因此无法保证iteratee函数将按顺序完成。

exapmle -

 var updateEventCredit = function ( userId, amount ,callback) {
    async.each(userId, function(id, next) {
    var incentiveData = new domain.incentive({
    user_id:userId,
        userName: id.userName,
        amount: id.totalJeeneePrice,
        description: id.description,
    schemeType:id.schemeType
    });

    incentiveData.save(function (err, result) {
        if (err) {
            next(err);
        } else {
                 domain.Events.findOneAndUpdate({
                    user_id: id.ids
                }, {
                    $inc: {
                        eventsCredit: id.totalJeeneePrice
                    }
                },{new:true}, function (err, result) {
                    if (err) {
                        Logger.info("Update status", err)
                        next(err);
                    } else {
                     Logger.info("Update status", result)
                     sendContributionNotification(id.ids,id.totalJeeneePrice);
                     next(null,null);       
                    }
                });
        }
    });
相关问题