如何使用node.js在node-zookeeper客户端中同时使用getChildren和getData方法

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

本文关键字:getChildren 方法 getData node 何使用 js 客户端 node-zookeeper      更新时间:2023-09-26

我是Node.js的新手。我正在尝试从npm(Github链接-https://github.com/alexguan/node-zookeeper-client)

我想了解如何将这个库中可用的getChildren和getData方法一起使用。(我知道这些使用回调)

其目的是迭代给定路径的所有子路径,获得所有子路径的数据,并在下一个子路径之前同步打印出来。

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();

上面的代码就是我所拥有的。输出如下

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

如果你看到数据,它会被打印为未定义。我希望每个都有正确的数据要打印而不是未定义的单个子节点。

有人能帮忙吗?谢谢

PS:数据在client.getData()的函数中打印,但不会分配给变量str.

getData是一个异步函数,您将无法将值返回给调用者。它将始终是未定义的,因为稍后会在不同的堆栈中调用回调。

要打印出数据,需要将console.log语句放入getData回调函数中。例如

  client.getData(newPath, function(error,data){
      if (error) {
          console.log(error.stack); 
          return;
      }
      console.log('Node: %s has DATA: %s', newPath, data ? data.toString() : '');
  });