Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Using the async lib - async.foreach with object

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');     });   
  1. Why does the final function not get called?

  2. How can I print the object index key?

like image 479
Ben Avatar asked Apr 30 '12 20:04

Ben


People also ask

Can I use async with forEach?

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.

Is NodeJS forEach async?

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.

What is async library in node JS?

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.

How do I use async await inside for loop?

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.


1 Answers

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'); });   
like image 112
stewe Avatar answered Oct 01 '22 12:10

stewe