繁体   English   中英

如何从async.whilst调用和express.js res.send()发送结果

[英]How do I send results from async.whilst call to and express.js res.send()

我正在使用图形数据库和seraph-api库来访问它。 我的问题是我正在尝试使用广度优先搜索进行异步图遍历。 我将关系的数据点发送到前端客户端,但数据永远不会到达那里。 我想知道我做错了什么。 我知道有一些代码味道。 我是节点的新手,并试图找出它。

注意:关系确实聚合到我设置的数组中,但是它们不会传递给响应。

我的代码如下:

var addRelations = function(node_id, res){
var relations = [];
// Read the first node from the database
db.read(node_id, function(err, initNode){
   var queue = [[initNode, 'out'], [initNode, 'in']];
   // Create a While loop to implement depth first search
   async.whilst(
       function () { return queue.length > 0},
   function (callback) {
       var NodeandDir = queue.shift();
       var node = NodeandDir[0]
       var dir = NodeandDir[1];
       // Lookup the relationships for the node in each direction
       db.relationships(node.id, dir, 'flows_to', function(err, relationships){
         //iterate through the relationships
         if(relationships.length === 0 && queue.length === 0){
           callback(err, relations)
         }
         _.each(relationships, function(relation){
            var node2id;
            relation.start === node.id ? node2id = relation.end : node2id = relation.start
            //read the other endpoint
            db.read(node2id, function(err, node2){
            // push the coordinates to relations
               relations.push([[node.lat, node.lng], [node2.lat, node2.lng]])
              //add the new node to the queue with the relationships
              queue.push([node2, dir])
        })
      })
    })
  },
  function(err, relations){
    console.log('Final Relations');
    console.log(relations);
    res.send(relations);
    }
   )
 })
}

router.get('/:id', function(req, res, next) {
  var node_id = req.params.id;
  addRelations(node_id, res);
});

我猜,你在_each之后没有调用“回调”,所以你的异步同时只会迭代

(relationships.length === 0 && queue.length === 0) 

是真的。

并建议,不要将数据逻辑与快速http通信混合使用。 在这种情况下,更好的决定是通过你的上层回调关系,它看起来像http控制器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM