Asynchronously print the contents of an array.
The following code logs a line for each element in an array:
function logArrayElements(val, n, arr, next) {
console.log('a[' + n + '] = ' + val);
next();
}
forEachAsync([2, 5, , 9], logArrayElements, () => {
console.log('done');
});
Asynchronously using thisArg
The following (contrived) example updates an object's properties from each entry in the array:
function Counter() {
this.sum = 0;
this.count = 0;
}
Counter.prototype.add = function (array) {
forEachAsync(array, function (val, n, arr, next) {
this.sum += entry;
++this.count;
next();
}, function () {
}, this);
};
var obj = new Counter();
obj.add([2, 5, 9]);
obj.count
obj.sum
Since the thisArg
parameter (this
) is provided to forEachAsync()
, it is passed to callback each time it's invoked, for use as its this
value.