How to use async-wait with MongoClient

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;

I get this error:

var test = await MongoClient.connect(url);
             ^^^^^^^^^^^
SyntaxError: Unexpected identifier

MongoClient.connect (url) returns a promise

Ultimately, I want to create a node module that will connect to mondoDB and will be used 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);
 }

Any suggestions?

+4
source share
2 answers

Is your module shell asynchronous? You need the keyword to awaitbe in an asynchronous function.

+1
source

How to wrap it in an asynchronous function?

var MongoClient = require('mongodb').MongoClient,
var url = "mongodb://localhost:27017/myDB";

var test = async function () {
  return await MongoClient.connect(url);
}

module.exports = test;
+4
source

Source: https://habr.com/ru/post/1669644/


All Articles