53

我正在使用节点异步库 - 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. 如何打印对象索引键?

4

2 回答 2

122

最终函数不会被调用,因为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');
});  
于 2012-04-30T20:43:46.283 回答
0

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

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

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

例子——

 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);       
                    }
                });
        }
    });
于 2017-04-23T18:32:32.983 回答