[英]Using native ES6 promises with MongoDB
我知道可以使用外部庫來宣傳 Mongo的Node驅動程序。 我很想知道ES6的承諾是否可以與MongoClient.connect
一起使用,所以我嘗試了這個(使用Babel 5.8.23進行轉換):
import MongoClient from 'mongodb';
function DbConnection({
host = 'localhost',
port = 27017,
database = 'foo'
}) {
return new Promise((resolve, reject) => {
MongoClient.connect(`mongodb://${host}:${port}/${database}`,
(err, db) => {
err ? reject(err) : resolve(db);
});
});
}
DbConnection({}).then(
db => {
let cursor = db.collection('bar').find();
console.log(cursor.count());
},
err => {
console.log(err);
}
);
輸出為{Promise <pending>}
。 與游標有關的任何事情似乎都會產生類似的結果。 有沒有辦法解決這個問題,還是我完全咆哮錯誤的樹?
編輯:節點版本4.1.0。
沒有什么可以解決的,這是預期的行為。 cursor.count()
返回一個promise,如果你想要這個值,你需要使用.then
,例如
DbConnection({}).then(
db => {
let cursor = db.collection('bar').find();
return cursor.count();
}
}).then(
count => {
console.log(count);
},
err => {
console.log(err);
}
);
或簡化
DbConnection({}).then(db => db.collection('bar').find().count()).then(
count => console.log(count),
err => console.log(err)
);
loganfsmyth響應的另一種語法(順便說一下)
cursor.count().then(function(cursor_count){
if(cursor_count){
// use cursor
}else{
// no results
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.