MongoDB 驱动程序提供了两种处理异步操作的选项:
当您不传递回调时,就像您的情况一样,它将返回一个承诺。
所以你需要在这里做出选择。但是,您无法选择的一个选项是“让这段代码同步运行”。
我更喜欢承诺:
function checkUpdateTime(last_updated){
var collection = db.collection(last_updated);
return collection.insert({ a : 1 }) // also async
.then(function() {
return collection.find({ a : 1 }).toArray();
});
}
checkUpdateTime('last_updated').then(function(updateTimes) {
console.log(updateTimes);
});
您总是可以更花哨并使用类似Promise.coroutine 的东西,这将使您的代码看起来更同步(即使不是):
const Promise = require('bluebird');
const MongoClient = require('mongodb').MongoClient;
let checkUpdateTime = Promise.coroutine(function* (db, last_updated){
let collection = db.collection(last_updated);
yield collection.insert({ a : 1 });
return yield collection.find({ a : 1 }).toArray();
});
Promise.coroutine(function *() {
let db = yield MongoClient.connect('mongodb://localhost/test');
let updateTimes = yield checkUpdateTime(db, 'foobar');
console.log(updateTimes);
})();
或async/await,使用Babel:
const MongoClient = require('mongodb').MongoClient;
async function checkUpdateTime(db, last_updated) {
let collection = db.collection(last_updated);
await collection.insert({ a : 1 });
return await collection.find({ a : 1 }).toArray();
}
(async function() {
let db = await MongoClient.connect('mongodb://localhost/test');
let updateTimes = await checkUpdateTime(db, 'foobar');
console.log(updateTimes);
})();