Async each vs forEach js
Asked Answered
W

1

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
)};
Witha answered 31/1, 2017 at 9:59 Comment(3)
synchronized vs unsynchronized (asynchronous)Quentin
The first will continue execution of any script after .each(), while the loop is still running. The second will complete the loop before any further script is executed.Touchmenot
See this answer and the ECMA specification for forEachRammer
D
14

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.

Deutoplasm answered 31/1, 2017 at 10:3 Comment(1)
also worth noting that async.each executes in parallel. async.eachSeries is available if needed.Autointoxication

© 2022 - 2024 — McMap. All rights reserved.