2016-04-27 66 views
1

'GetUsers'函數正在運行,並且它按預期返回正確的值。但是,res.send(用戶)在嵌套函數完成之前正在運行,因此該值未定義。我已經嘗試從嵌套函數中執行res.send(用戶),但它不能識別該函數。我也嘗試過使用返回用戶,但無法使其工作。任何幫助,將不勝感激!res.send()在嵌套函數完成之前運行,值爲

app.get('/GetUsers', function (req, res){ 
    var url = 'mongodb://localhost:27017/users'; 
    var users = ""; 
    MongoClient.connect(url, function (err, db) { 
     if (err) { 
      console.log('Unable to connect to the mongoDB server. Error:', err); 
     } else { 
      console.log('Connection established to', url); 
      // Get the documents collection 
      var collection = db.collection('users'); 
      // Get some users 
      collection.find().toArray(function (err, res) { 
       if (err) { 
        console.log(err); 
       } else { 
        console.log('Got Information from db.'); 
       } 
       //Close connection 
       db.close(); 
       console.log('db closed.'); 
       users = res; 
       console.log(users); 
      }); 
     } 
    }); 
res.send(users); 
}); 
+1

的可能的複製[如何返回從一個異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-呼叫) –

回答

1

只需將您的回調中移動res.send(users)前/你叫console.log(users)後。

您在toArray通話重用變量res,所以請有其重命名爲:在users = res;...toArray(function (err, res)......toArray(function (err, result)...同時也users = result;

+0

我已經嘗試過,但我得到一個TypeError:res.send不是一個函數。 – Matrix

+0

Ups。對不起,監督你重用了變量'res'。請重新命名'...指定者(函數(ERR,RES)...''到...指定者(函數(ERR,結果)...'也做,在'用戶=資源;''給用戶= 。結果;' – CFrei

+0

感謝您的答覆不幸的是我已經嘗試這樣做,仍然res.send(用戶)嵌套函數完成之前運行 – Matrix

0

這是異步調用,它將發送響應並且不會等待數據庫連接功能。 在回撥函數中寫入res.send
在您關閉數據庫連接的地方編寫res.send函數。

這裏是詳細How do I return the response from an asynchronous call?

+0

嗨阿薩德,我都試過,但我得到一個類型錯誤:res.send不是。一個函數 – Matrix

+0

使用不同的變量與函數'collection.find().toArray('function(err,res){' 這是結束res功能@Matrix – Asad

+0

使用結果或數據代替res在這個函數@Matrix – Asad

0

找到了答案!

我需要在我的回調使用res.send(用戶)我已經關閉了數據庫之後由用戶建議上述人士指出。然而,僅此一項工作不如res.send(用戶)錯誤,因爲它不被識別爲函數。我不得不使用res.send({「匹配」:用戶}),然後訪問這樣的客戶端我響應對象:response.matched.objects等

感謝您的幫助大家!

相關問題