我'm new to Node.js. I'我试图从npm使用node-zookeeper-client(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
如果您看到DATA,它将被打印为未定义 . 我希望打印每个子节点的正确数据而不是未定义 .
有人可以帮忙吗?谢谢 .
PS:数据在client.getData()函数内打印,但没有被赋值给变量str .
1 回答
getData
是一个异步函数,您将无法将该值返回给调用者 . 它总是未定义的,因为稍后在不同的堆栈中调用回调 .要打印出数据,需要将
console.log
语句放在getData回调函数中 . 例如