2016-06-12 86 views
0

我無法將數據推送到組合數據數組中,而不是將數據推送到閉包函數中。我發現我需要使用與數據庫相關的程序的閉包。我是節點js的新手, javascript.and它的異步性讓我陷入了這樣的困境。任何人都可以幫助我怎麼處理這個問題。無法將數據推送到組合數據數組

combineddata=[]; 
     if(err){ 
      res.send(err); 
     }else{ 
      for(i=0;i<data.length;i++){ 

      (function(){ 
       x=i; 

       teststats.addTestStats.find({Testid:data[x].Testid},function(err,testdata){ 
        if(err){ 
         res.send(err); 
        }else{ 
         //console.log(testdata+"no"+x+"yes"+i); 
         console.log(x,i) 
         stat.push(testdata); 
         combineddata.push("examplepush"); 
        } 

       }); 
      })(); 


      } 
     } 
res.send(combineddata); 

回答

0

我與「不能推」假設你的意思,你推入combineddata"examplepush"沒有在你的HTTP響應顯示。這是因爲數據庫查詢是異步執行的,並且回調中的推送代碼實際上是在已完成res.send並從處理程序返回後運行的。

你可以做的是重構你的代碼,這樣你只需要在那裏執行一個查詢而不是循環中的幾個查詢,然後你就可以在數據庫查詢回調中執行res.send。

嘗試使用這樣的事情作爲你的積木代替for循環:

var testIds = data.map(function (elem) { return elem.Testid }); 
teststats.addTestStats.find({Testid: {$in: testIds}}, function (err, testdata) { 
    res.send(testdata) // Testdata is now an array matching all Testid's you queried for 
} 
+0

http://stackoverflow.com/questions/38160209/getting-parent-index-inside-a-custom- directice可以幫助你解決這個問題 – vanquishers