How to use getChildren and getData method together in node-zookeeper-client using Node.js?

I'm new to Node.js. I'm trying to use node-zookeeper-client from npm(Github link - https://github.com/alexguan/node-zookeeper-client)

I wanted to understand how to use getChildren and getData method available in this library together.(I understand these uses callbacks)

The aim is, to iterate through all the children of a given path and get the data of all children and print it out sychronously before going to next children.

var zookeeper = require('node-zookeeper-client');
var client = zookeeper.createClient('localhost:2181');
var path =  "/Services/Apache";
var tmpChildren = [];

function getChildren(client,path){

console.log('path value received is..', path );
client.getChildren(path, function (error, children, stats) {
    if (error) {
        console.log(error.stack);
        return;
    }

    console.log('Children are: %s', children);
    tmpChildren = String(children).split(",");
    var newPath="";

   for(var i=0; i < tmpChildren.length ; i++)
   {
      newPath = path+'/'+tmpChildren[i];
      console.log('children is %s',tmpChildren[i]);
      var str = client.getData(newPath, function(error,data){
             if (error) {
              return error.stack; 
          }
             return data ? data.toString() : undefined;

      });
      console.log('Node: %s has DATA: %s', newPath, str);
  }

}

);

}

client.once('connected', function () 
    {
    console.log('Connected to the server.');
    getChildren(client,path);


});

client.connect();

The above piece of code is what I have. The output is as follows

Connected to the server.
path value received is.. /Services/Apache
Children are: Instance4,Instance3,Instance2,Instance1
children is Instance4
Node: /Services/Apache/Instance4 has DATA: undefined
children is Instance3
Node: /Services/Apache/Instance3 has DATA: undefined
children is Instance2
Node: /Services/Apache/Instance2 has DATA: undefined
children is Instance1
Node: /Services/Apache/Instance1 has DATA: undefined

If you see the DATA it's getting printed as undefined. I expect the correct data for each individual child node to be printed instead of undefined.

Can anyone please help? Thanks.

PS: The data gets printed inside the function of client.getData(), but not getting assigned to variable str.

getData is an asynchronous function, you will not be able to return the value back to the caller. It will always be undefined since the callback is invoked in a different stack in a later time.

To print out the data, you need to put console.log statement inside of the getData callback function. e.g.

  client.getData(newPath, function(error,data){
      if (error) {
          console.log(error.stack); 
          return;
      }

      console.log('Node: %s has DATA: %s', newPath, data ? data.toString() : '');
  });