简体   繁体   中英

Callback in async.each

I have a problem with async. For each element i have to call a async function

this is my example object

    [ { bar: 'foo',
    buz: [ [Object], [Object], [Object] ] },
  { bar: 'foo2', buz: [ [Object] ] } ]

  -----
  buz = { _id: '55555555ffffff000010200a', name: 'foo }

for each buz._id i have to call another async method "item.someAsyncCall"

async.each(req.body.roles,
    function(item, callback){
        callback();

        async.each(item.site,
            function(item, callback){


                 item.someAsyncCall(function (){
                  // Async call is done, alert via callback
                  console.log('inside==> '+result);
                  callback();
                });

            },
            function(err){
                if (err) {
                    console.log('A file failed to process');
                } else {
                    console.log('FIRST');
                }
            }
        );


    },
    function(err){
        if (err) {
            console.log('A file failed to process');
        } else {
            console.log('Second');
        }
    }
);


console.log('OUT ==>');

The result:

inside ==> false

inside ==> true

inside ==> false

FIRST

inside ==> false

FIRST

But Never call Second Never call OUT ==>

For the asynchronous equivalent of two nested (parallel) for-loops, try

async.each(outerList, function (item, outerCallback) {
    async.each(item.innerList, function (innerItem, innerCallback) {
        doSomethingAsync(innerItem, innerCallback);
    }, outerCallback);
}, function (err) {
    // everything is done, or you get an error
});

A simpler approach might be to flatten out the list, and just use a single async.each over that flattened list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM