【问题标题】:iterate each object in array and populate each element of the array with result. asynchronously迭代数组中的每个对象并用结果填充数组的每个元素。异步
【发布时间】: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 函数中使用 Asynceachma​​p 来解决所有这些问题,但得到结果没有什么明智的。堆栈溢出社区可能会找到一些聪明的解决方案。请帮忙。

【问题讨论】:

  • 你能告诉我们你的异步代码吗?这应该适用于您的用例。你想要一个map。第一个参数是您的数组,第二个是检索所需内容的函数,然后在最后一个函数中,您有一个包含所有结果的数组,然后您只需要将其连接起来。

标签: arrays json node.js loops asynchronous


【解决方案1】:

我不熟悉node-opcua,但假设session.browse() 也是异步的。那么这样的事情可能会奏效吗?

var async = require('async');

async.map(buf,
  function(reference, callback) {

    session.browse(reference.nodeId, function (err, result) {
      callback(err, result);
    });

  }, function(err, results) {

    // results is now an array of all single results
    NodesTree.subf = results;

  });

【讨论】:

  • 实际上,这帮助我解决了问题。代码比这更大,但我得到了正确的方向)谢谢。
猜你喜欢
  • 2017-12-25
  • 2014-02-15
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 2013-12-27
  • 2021-04-15
  • 1970-01-01
  • 2018-08-23
相关资源
最近更新 更多