【发布时间】:2019-05-30 17:13:10
【问题描述】:
工作案例:
当我们调用一个异步函数并且该函数返回一个 promise resolve() 时,async await 工作正常
不工作的情况:
async await 不适用于 mongo DB 查询
试过 then(),异步/等待
我有 2 个 JS 文件。
在 one.js 文件中,我正在导入 functionone.js 中的函数
工作案例:
当 one.js 看起来像时
var functiononestatus = transactions.functionone(req.session.email).then((came) => {
console.log(came); // getting `need to be done at first` message
console.log("exec next")
});
functionone.js 的样子
module.exports.functionone = functionone;
async function functionone(email) {
return await new Promise((resolve, reject) => {
resolve('need to be done at first')
});
});
NOT WORKING CASE(当需要执行 mongo db 查询时):
当 one.js 看起来像时
var functiononestatus = transactions.functionone(req.session.email).then((came) => {
console.log(came); // getting undefined
console.log("exec next")
});
functionone.js 的样子
module.exports.functionone = functionone;
async function functionone(email) {
//mongo starts
var collection = await connection.get().collection('allinonestores');
await collection.find({
"email": email
}).toArray(async function(err, wallcheck) {
return await new Promise((resolve, reject) => {
resolve(wallcheck[0])
});
});
【问题讨论】:
-
第二个,
functionone没有返回任何东西,因此undefined -
实际上我们在
wallcheck[0]中获取值(在第二个函数中)但是code one.js 变得未定义,尽管我们在wallcheck[0]中有值 -
是的,因为您的
functionone没有返回任何内容。 -
我明白,但问题是你?
-
它没有返回任何内容,因为函数中没有
return语句。尝试使用return返回 Promise。
标签: javascript node.js mongodb promise async-await