我想要同步獲取mongodb實例。我知道這不是建議,但我只是試驗,並想知道爲什麼這不起作用。 this.db
在等待10秒後仍然未定義,通常異步代碼在小於500毫秒內得到它。爲什麼我無法通過同步等待來獲取異步等待的值?
Repository.js:
var mongodb = require('mongodb');
var config = require('../config/config');
var mongoConfig = config.mongodb;
var mongoClient = mongodb.MongoClient;
class Repository {
constructor() {
(async() => {
this.db = await mongoClient.connect(mongoConfig.host);
})();
}
_getDb(t) {
t = t || 500;
if(!this.db && t < 10000) {
sleep(t);
t += 500;
this._getDb(t);
} else {
return this.db;
}
}
collection(collectionName) {
return this._getDb().collection(collectionName);
}
}
function sleep(ms) {
console.log('sleeping for ' + ms + ' ms');
var t = new Date().getTime();
while (t + ms >= new Date().getTime()) {}
}
module.exports = Repository;
app.js:
require('../babelize');
var Repository = require('../lib/Repository');
var collection = new Repository().collection('products');
JS是單線程的,你忙循環的定義存在防止被設置的值。如果JS花費整個時間循環,它就沒有機會分配'db'。你最好把這個問題改寫爲「我應該如何重寫這段代碼才能工作」。 – loganfsmyth
我認爲這個問題應該至少部分地在問題標題中被重現。 「這個代碼」需要讀者窺視問題的主體。 – jstice4all
簡而言之,您無法從同步函數中返回異步值。你根本無法做到這一點。您的繁忙等待循環不會像Javascript運行的方式工作。因爲你永遠不允許事件循環來處理下一個事件,所以你的數據庫完成回調將永遠不會被調用。你必須編寫一個異步結果。回覆一個承諾或通過回調。 – jfriend00