MongoDBのドライバは、非同期操作を処理するための2つのオプションを提供していますあなたの場合のようにコールバックを渡すと、約束が返されます。
だから、ここで選択をする必要があります。あなたが選択できない1つの選択肢は、"このコードを同期させる"です。
私は約束を好む:
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
のようなものを使用することができ、あなたのコードを作成することをもう少し同期見て(それがない場合でも):
Babelを使用して
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
、:
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);
})();
'"あなたは""を選択することはできません。彼はすることができます。 'async/await'を使用します。 –
@vp_arthはまだそれを同期させません(ヒントは名前に "async" ;-)です)。それは、私がそれを例として追加した理由です。 – robertklep