2015-03-02 64 views
0

我正在使用圖形數據庫和seraph-api庫來訪問它。我的問題是,我正在嘗試使用廣度優先搜索來執行異步圖遍歷。我將關係的數據點發送到前端客戶端,但數據永遠不會到達那裏。我想知道我做錯了什麼。我知道有一些代碼味道。我是新來的節點,並試圖找出它。如何發送來自async.whilst的結果和express.js res.send()

注意:這些關係確實聚合到我設置的數組中,但它們不會傳遞給響應。

我的代碼如下:

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

回答

0

我猜,你沒叫_each後「回調」,讓你的異步而將迭代僅當

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

是真實的。

而建議,不要混合數據邏輯與快速http通信。在這種情況下,更好的決定是將你的關係傳遞給上層回調,這看起來像http控制器。

+0

謝謝你對此的幫助。如果您有機會,我想更多地與您談談您的建議。我可以使用一些幫助重構和理解你的意思。再次感謝。 – shkfnly 2015-03-02 15:09:34

+0

當然。在你的例子中,你將響應對象作爲第二個參數傳遞給addRelations函數。所以最好是addRelations只有一個回調函數,並且將數據庫結果傳遞給它。因此,在上一級,您將得到如下所示的不等式: app.use(「/ add」,function(req,res){addrlations(node_id,function(err,relations){err){} //登錄或響應客戶端 res.end(relations); }); }); 在這種情況下,您的代碼將更接近經典的模型控制器模式 – 2015-03-02 15:16:48

相關問題