我想要同步获取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