当我运行它时(使用带有--harmony的节点v7.5):
var MongoClient = require('mongodb').MongoClient,
var url = "mongodb://localhost:27017/myDB";
var test = await MongoClient.connect(url);
module.exports = test;
我收到此错误:
var test = await MongoClient.connect(url);
^^^^^^^^^^^
SyntaxError: Unexpected identifier
MongoClient.connect(url)会返回一个承诺
我最终想要实现的是创建一个将连接到mondoDB的节点模块,并且可以在以下示例中使用:
var db = require('../utils/db'); //<-- this is what I want to create above
col = db.collection('myCollection');
module.exports.create = async fuction(data) {
return await col.insertOne(data);
}
有什么建议吗?
答案 0 :(得分:4)
将它包装在异步函数中怎么样?
var oms = new OverlappingMarkerSpiderfier (...) ;
// Create this function
function addClickListenerToMarker(marker, onClickListener) {
oms.addListener('click', function (markerArg, eventArg) {
if (marker == markerArg)
onClickListener(marker, eventArg);
});
}
// Add a click listener to your marker
var myMarker = ...
addClickListenerToMarker(myMarker, function (marker, event) {
alert('I have been clicked');
});
答案 1 :(得分:4)
我解决了这个问题,只打开了一个连接:
<强> db.js 强>
const MongoClient = require('mongodb').MongoClient;
let db;
const loadDB = async () => {
if (db) {
return db;
}
try {
const client = await MongoClient.connect('mongodb://localhost:27017/dbname');
db = client.db('dbname');
} catch (err) {
Raven.captureException(err);
}
return db;
};
module.exports = loadDB;
<强> index.js 强>
const loadDB = require('./db');
const db = await loadDB();
await db.collection('some_collection').insertOne(...);
答案 2 :(得分:1)
您的模块包装器也是异步功能吗?您需要await
关键字位于异步函数中。