【发布时间】:2016-04-06 16:56:04
【问题描述】:
我需要有关数组异步迭代功能的帮助。我在 nodejs 中使用 node-opcua 库。有函数session.browse(nodeId, result) 现在代码看起来像:
NodesTree = {
"NodesTree":{
"name":"SYM:",
"subf":[]
}
};
the_session.browse("ns=1;s=SYM:", function(err, browse_result){
if(!err) {
var buf = [];
browse_result[0].references.forEach(function(reference) {
if (reference1.browseName.namespaceIndex > 1) {
buf.push(reference);
}
});
NodesTree.subf = buf;
}
});
结果我得到 references of SYM: 文件夹示例:
[{"referenceTypeId":"ns=0;i=35","isForward":true,"nodeId":"ns=6;s=S71500ET200MP station_1","browseName":{"namespaceIndex":6,"name":"S71500ET200MP station_1"},"displayName":{"text":"S71500ET200MP station_1","locale":"en"},"nodeClass":"Object","typeDefinition":"ns=0;i=61"}]
我在 opc 中有这样的节点结构:
->SYM:
-->PLC
--->PLC_name
---->global_tag <variable>
---->global_tag1 <variable>
---->block
------>blok_tag1 <variable>
------>block_tag2 <variable>
任务是制作一个完整的 JSON 对象作为树以供进一步使用。
逻辑是:对于references数组中的每个元素,获取nodeId值并浏览元素的references并分配为元素。 subf = 参考。
最终结果类似于:
NodesTree = {
"NodesTree":{
"name":"SYM:",
"subf":[
{attributes of PCL structure got by **browse**() + subf:[{ attributes of PLC_name by browse(), subf:
[{....and here again attributes and subf] }, {if no subf just assign subf; [] }]
]
}
};
因此需要为每个引用调用 session.browse() 并最终绑定到一个对象。
我尝试在 series 函数中使用 Async 库 each 和 map 来解决所有这些问题,但得到结果没有什么明智的。堆栈溢出社区可能会找到一些聪明的解决方案。请帮忙。
【问题讨论】:
-
你能告诉我们你的异步代码吗?这应该适用于您的用例。你想要一个map。第一个参数是您的数组,第二个是检索所需内容的函数,然后在最后一个函数中,您有一个包含所有结果的数组,然后您只需要将其连接起来。
标签: arrays json node.js loops asynchronous