11

Can someone explain me the different between this two:

async.each(items, function (item, callback) {
    // Do something
});

OR :

items.forEach(function(item) {
 // Do something
)};
Avihay m
  • 481
  • 1
  • 4
  • 17

1 Answers1

13

async.each

is non blocking (asynchronous), means the execution of your script goes on while it's running. It's also running parallel, means that multiple items are processed at the same time. It's a method provided by an external library, I guess async. It's not a native Javascript feature and not added to Array.prototype, thus you can't write myArray.each.

Array.forEach

is blocking (synchronous), means the execution of your script waits till it's finished. It's running serial, means that each item is processed after the former item has been processed. forEach is a native Javascript function (spec) & defined on the Array.proptotype, thus you can simply write myArray.forEach instead of Array.forEach(myArray). If you, for example, push to an array in your forEachloop, then you can access the pushed values in the lines after the forEach call.

Marc Dix
  • 1,565
  • 10
  • 26
  • 1
    also worth noting that `async.each` executes in parallel. `async.eachSeries` is available if needed. – Robbie Jan 31 '17 at 21:11