2014-10-10 31 views
0

我使用node.js和貓鼬進行包括get請求在內的多個HTTP請求。我的get函數將具有相當多的功能,並且可以輕鬆處理許多數據,我嘗試讓局部變量存儲來自mongo的返回值。例如:保存GET請求返回從node.js和貓鼬變量

router.get('/getstuff/:test', function(req, res) { 
    var testId = req.params.test; 
    var returnStuff = null; 

    var collection = req.collection; 

    collection.find({userIdd : testId}, function(err, data){ 
     if (err) console.log(err); 
     else { 
      console.log(data); // works, data is shown in log 
      returnStuff = data; // does not work, data is not saved to returnStuff 
     } 
    }); 

    console.log(returnStuff); // undefined 
    res.send(); 
}); 

我試圖得到什麼我從數據庫中,數組的returnStuff變回來,但由於關閉,我不能這樣做。這可能看起來微不足道,但正如我所說,我會有更多的操作,這將真正簡化事情。

任何人有任何提示嗎?真的很感激它。

感謝

+0

另請注意「[如何避免Node.js中異步函數的長嵌套](http://stackoverflow.com/questions/4234619/how-to-avoid-long-nesting-of-asynchronous-functions -in-node-js)「 – 2014-10-10 02:22:18

回答

1

collection.find是異步執行的,所以充滿returnStuff之前執行res.send。你可以完全擺脫它,只需res.send(數據)在回調中。

這應該工作:

router.get('/getstuff/:test', function(req, res) { 
    var testId = req.params.test; 
    var returnStuff = null; //optional, remove if you don't need it for anything else 

    var collection = req.collection; 

    collection.find({userIdd : testId}, function(err, data){ 
     if (err) console.log(err); 
     else { 
      console.log(data); // works, data is shown in log 
      returnStuff = data; 
      collection.somethingelse(function(err,data2){ 
       returnStuff += data2 
       res.send(returnStuff); 
      });     
     } 
    }); 

}); 

,如果你有很多這樣的操作,你可以讓他們到圖書館,或使用像異步 退房更多信息這個巨大的資源庫:http://book.mixu.net/node/ch7.html

Read this post too, and you'll know EVERYTHING!

+0

問題是,我將在該函數中使用其他mongoose數據庫調用,並且會從這些數據中獲取更多數據。出於這個原因,我需要訪問returnStuff,然後使用我將獲得的其他數據。 此外,據我瞭解(雖然不是很多,我是新的node.js),我只能使用res.send()一次。之後我想返回一個總體結果,就像returnStuff那只是計算的數據。 – intl 2014-10-10 02:10:27

+0

在這種情況下,你將不得不嵌套回調,或者使用類似async的庫來同步執行你的操作:看看我在回答中提供的鏈接 – xShirase 2014-10-10 02:13:16

+0

我使用了嵌套回調。來自Python和C++,node.js是......不同的。 – intl 2014-10-10 05:40:24