Node.js - 使用异步库 - async.foreach 与对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10390041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:38:40  来源:igfitidea点击:

Node.js - Using the async lib - async.foreach with object

node.jsloopsobjectasynchronousnode-async

提问by Ben

I am using the node asynclib - https://github.com/caolan/async#forEachand would like to iterate through an object and print out its index key. Once complete I would like execute a callback.

我正在使用节点异步库 - https://github.com/caolan/async#forEach并想遍历一个对象并打印出它的索引键。完成后,我想执行回调。

Here is what I have so far but the 'iterating done'is never seen:

这是我迄今为止所拥有但'iterating done'从未见过的:

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

    }, function() {
        console.log('iterating done');
    });  
  1. Why does the final function not get called?

  2. How can I print the object index key?

  1. 为什么不调用最终函数?

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

回答by stewe

The final function does not get called because async.forEachrequires that you call the callbackfunction for every element.

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

Use something like this:

使用这样的东西:

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

回答by Shashwat Gupta

async.each is very useful and powerful function which is provided by Async Lib .it have 3 fields 1-collection/array 2- iteration 3-callback the collection is referred to the array or collection of objects and iteration is refer to the each iteration and callback is optional . if we are giving callback then it will return the response or say result which you want to show you in the frontend

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

Applies the function iteratee to each item in coll, in parallel. The iteratee is called with an item from the list, and a callback for when it has finished. If the iteratee passes an error to its callback, the main callback (for the each function) is immediately called with the error.

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

Note, that since this function applies iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order.

请注意,由于此函数将 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);       
                    }
                });
        }
    });