MongoDB의 드라이버는 비동기 작업을 처리하는 두 가지 옵션을 제공합니다 귀하의 경우와 마찬가지로 콜백을 전달하면 약속이 반환됩니다.
여기에서 선택해야합니다. 선택할 수없는 선택은 "이 코드를 동기식으로 실행"입니다.
나는 약속을 선호 : 당신은 항상 좀 더 화려한 가서 Promise.coroutine
같은 것을 사용할 수
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);
});
, 코드를 만들 것 보면 조금 (그렇지 않은 경우에도) 더 동기 :
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"입니다. ;-). 그것은 그것을 좋아할지도 모르지만, 그래서 나는 이것을 예제로 추가했습니다 : D – robertklep