I am using the node async lib - https://github.com/caolan/async#forEach and would like to iterate through an object and print out its index key. Once complete I would like execute a callback.
Here is what I have so far but the 'iterating done'
is never seen:
async.forEach(Object.keys(dataObj), function (err, callback){ console.log('*****'); }, function() { console.log('iterating done'); });
Why does the final function not get called?
How can I print the object index key?
forEach is not designed for asynchronous code. (It was not suitable for promises, and it is not suitable for async-await.) For example, the following forEach loop might not do what it appears to do: const players = await this.
forEach Asynchronous? It is not asynchronous. It is blocking. Those who first learned a language like Java, C, or Python before they try JS will get confused when they try to put an arbitrary delay or an API call in their loop body.
Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with Node. js and installable via npm i async , it can also be used directly in the browser.
You need to place the loop in an async function, then you can use await and the loop stops the iteration until the promise we're awaiting resolves. You could also use while or do.. while or for loops too with this same structure. But you can't await with Array.
The final function does not get called because async.forEach
requires that you call the callback
function for every element.
Use something like this:
async.forEach(Object.keys(dataObj), function (item, callback){ console.log(item); // print the key // tell async that that particular element of the iterator is done callback(); }, function(err) { console.log('iterating done'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With