本文介绍了我如何在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.

这篇关于我如何在MongoClient中使用async-await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:28