node.js - Why does my function comprised of asynchronous functions not returning correct value? (NodeJS)
问题描述
A variable which is assigned within async functions is not returning the expected output.
I am currently writing a NodeJS function that finds an object from a MongoDB database (the database works perfectly) and returns an object if it is found. The problem is that the functions' comprising async functions don't wait until the previous functions are finished. I am relatively new to JS and NodeJS, so it may be that I am misunderstanding how the async functions act.
async function findUserByEmail (userEmail) {
var mg = require('mongodb').MongoClient;
var user;
await mg.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, async function(err, db){
var dbo = db.db(myDB);
var query = { email : userEmail };
await dbo.collection("Users").findOne(query).then((result)=>{
user = result;
db.close();
});
});
return user;
}
I am trying to return the value assigned to "user" within the "findOne(query)" function, however, the value returned is always "undefined".
解决方案
您正在混合回调和异步调用。所以让我把它清理干净。瞧,这里你做了一些应该工作的东西(你有一些我不知道的值,例如 myDB 和 url)。
async function findUserByEmail (userEmail) {
var mg = require('mongodb').MongoClient;
var db = await mg.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
var result;
// Add a Try/Catch to capture any errors,
// such that the database can still be closed
try {
var dbo = db.db(myDB);
var query = { email : userEmail };
result = await dbo.collection("Users").findOne(query);
} catch (error) {
throw error;
} finally {
db.close();
}
return result;
}
注意:我建议在应用程序启动时打开一次 MongoDB 连接,在它因任何原因关闭时重新打开它,并在应用程序停止时关闭它,因为为每个请求打开一个新连接会增加一些显着的开销(想想可能会慢 25 倍)。
推荐阅读
- java - 为什么删除根节点会保留左子树而不保留我的右子树?
- vue.js - Vue从服务器接收数据
- html - 键盘 TAB 选择不可见
- docker - 更新 docker(18.09.0) 会导致错误
- swagger - 是否可以在 swagger 中使用整个原始字符串作为参数
- python - 如何通过 form.error.as_text 在模板中引发错误?
- php - 如何正确实现 AMP 表单 POST 提交?
- python - 为什么 Python tkinter 标签小部件不更新?
- tomcat - Google Cloud Platform:无法从外部访问外部 IP 地址
- python - 欧拉项目 #641 Python 3.6 - Numpy