我如何在MongoClient中使用async-await

我如何在MongoClient中使用async-await

问题描述:

运行此命令时(将节点v7.5.0与--harmony一起使用):

When I run this (using node v7.5.0 with --harmony):

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)确实返回了诺言

MongoClient.connect(url) does return a promise

我最终要实现的目标是创建一个节点模块,该模块将连接到mondoDB并可以使用,如以下示例所示:

What I ultimately want to achieve is to create a node module that will connect to a mondoDB and will be usable as in the following example:

 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);
 }

有什么建议吗?

您的模块包装器也是异步函数吗?您需要await关键字才能使用异步功能.

Is your module wrapper an async function as well? You need the await keyword to be in an async function.