简体   繁体   中英

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. 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

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

is true.

And the advice, not to mix data logic with express http communication. In this case better decision is to pass your relations for upper callback, which just look like http controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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