在异步/等待中使用猫鼬承诺 [英] Using mongoose promises with async/await
问题描述
我试图摆脱使用Mongoose Promise与Node.js的async/await功能的束缚.调用函数printEmployees
时,我想保存由orderEmployees
函数查询的员工列表.虽然orderEmployees
内的console.log
语句返回期望的查询,而printEmployees
内的console.log
却返回undefined
,这表明我没有正确返回承诺.
I'm trying to get the hang of using Mongoose promises with the async/await functionality of Node.js. When my function printEmployees
is called I want to save the list of employees which are queried by the orderEmployees
function. While, the console.log
statement inside orderEmployees
returns the expected query, the console.log
inside of printEmployees
returns undefined
, suggesting that I'm not returning the promise correctly.
我对承诺完全陌生,以至于我没有正确理解范例……非常感谢您的帮助.
I'm new to promises so entirely possible that I'm not correctly understanding the paradigm... any help is much appreciated.
printEmployees: async(company) => {
var employees = await self.orderEmployees(company);
// SECOND CONSOLE.LOG
console.log(employees);
},
orderEmployees: (companyID) => {
User.find({company:companyID})
.exec()
.then((employees) => {
// FIRST CONSOLE.LOG
console.log(employees);
return employees;
})
.catch((err) => {
return 'error occured';
});
},
推荐答案
您需要return
您的Promise
,否则您正在等待返回undefined
的函数.
You need to return
your Promise
, otherwise you are awaiting on a function that returns undefined
.
orderEmployees: (companyID) => {
return User.find({ company:companyID }).exec()
}
当前,您正在等待非承诺,因此下一行代码将立即运行;在您真正想要等待的承诺真正解决之前.
Currently, you're awaiting a non-Promise so next-line code will run immediately; before the Promise you really want to await actually resolves.
同样非常重要,您应该在.catch
处理程序中使用throw
而不是return
.或者更好的是,根本不包括.catch
,而让实际错误冒出承诺链,而不是用您自己的非描述性'error occured'
消息覆盖它.
Also really important, you should throw
instead of return
in your .catch
handler. Or better yet, don't include .catch
at all and let the the actual error bubble up the promise chain, instead of overriding it with your own non-descriptive 'error occured'
message.
这篇关于在异步/等待中使用猫鼬承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!