简体   繁体   English

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

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

I am using a graph database and the seraph-api library in order to access it. 我正在使用图形数据库和seraph-api库来访问它。 My problem is that I am trying to do an asynchronous graph traversal using a breadth first search. 我的问题是我正在尝试使用广度优先搜索进行异步图遍历。 I am sending the data points of the relationship to a frontend client, but the data never gets there. 我将关系的数据点发送到前端客户端,但数据永远不会到达那里。 I am wondering what I am doing wrong. 我想知道我做错了什么。 I know there is some code smell. 我知道有一些代码味道。 I am new to node and trying to figure it out. 我是节点的新手,并试图找出它。

Note: The relationships are indeed aggregated into the array that I set up, however they are not passed on to the response. 注意:关系确实聚合到我设置的数组中,但是它们不会传递给响应。

My code is as follows: 我的代码如下:

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

I guess, that you didn't call "callback" after _each, so your async while will iterate only when 我猜,你在_each之后没有调用“回调”,所以你的异步同时只会迭代

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

is true. 是真的。

And the advice, not to mix data logic with express http communication. 并建议,不要将数据逻辑与快速http通信混合使用。 In this case better decision is to pass your relations for upper callback, which just look like http controller. 在这种情况下,更好的决定是通过你的上层回调关系,它看起来像http控制器。

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

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