Reputation: 105
I'm trying to build an asynchronous forEach
function, but unfortunately it returns the value undefined
instead of the content of the array for which I had hoped for. What am I doing wrong?
function asyncforEach(array, cb) {
array.forEach(function(){
setTimeout(cb, 0);
});
}
asyncforEach([1,2,3,4], function(i) {
console.log(i)
});
Upvotes: 0
Views: 352
Reputation: 72857
Pass the variable (value
) to the callback, in setTimeout
.
function asyncforEach(array, cb) {
array.forEach(function(value){ // value: The current array entry
setTimeout(cb, 0, value); // Pass it to the callback when setTimeout invokes it.
});
}
asyncforEach([1,2,3,4], function(i) {
console.log(i)
});
Any parameters passed to setTimeout
after the function
and delay
parameters, are passed to the callback:
var timeoutID = scope.setTimeout(function[, delay, param1, param2, ...]);
Upvotes: 4
Reputation: 68655
You missed to get the item
in the forEach
function parameter and pass the item into the setTimeout
, Also call the cb
function with passed array item into it. This will force the cb
function to be called inside the arrow function, when the time will be out.
function asyncforEach(array, cb) {
array.forEach(function(i) {
//-----------------^---
setTimeout( () => cb(i), 0);
//----------^^^^^^^^^^^----
});
}
asyncforEach([1,2,3,4], function(i) {
console.log(i)
});
Upvotes: 2