Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async each vs forEach js

Can someone explain me the different between this two:

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

OR :

items.forEach(function(item) {
 // Do something
)};
like image 818
Avihay m Avatar asked Jan 31 '17 09:01

Avihay m


1 Answers

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.

like image 88
Marc Dix Avatar answered Oct 24 '22 19:10

Marc Dix