简体   繁体   中英

async.each/forEach third parameter(callback) is triggered after each interval

Hi
I have function that accepts an two arrays and callback function, I am iterating over one of the arrays using async.each(and tried async.forEach and both have same result), everything works fine but the callback that I am receiving as the parameter, which is sent as the third parameter is triggered after the first iteration. Here is my code.

 function itemLikes(instruments,likes, finalCallback){ var items = []; if(instruments.length >= 1){ async.forEach(instruments, function(instrument,cb){ if(likes){ if(likes.indexOf(instrument._id.toString()) !== -1){ instrument.liked = 1; cb(items.push(instrument)) } else{ cb(items.push(instrument)) } } else{ cb(items.push(instrument)) } }, function(err){ finalCallback(items) }) } else{ finalCallback(items) } 

}

This is what I understood from the documentation, but my finalCallback is triggered right after my first iteration completes.

Thanks and Regards.

The reason the callback that receiving as the parameter (finalCallback()) is triggered after the first iteration is because asyc.each()'s callback (cb) is called with a non-null value. When it's called with a non-null value, async.each()'s final callback gets called which then calls your finalCallback(). You need to do something like this:

if(likes){
  if(likes.indexOf(instrument._id.toString()) !== -1){
    instrument.liked = 1;
    items.push(instrument);
    cb()
  } else{
    items.push(instrument);
    cb()
  }
} else{
  items.push(instrument);
  cb()
}

It seems like your logic above can be simplified as following:

if(likes && likes.indexOf(instrument._id.toString()) !== -1){
    instrument.liked = 1;
}
items.push(instrument);
cb()

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