我正在尝试将 Mongoose Promise 与 Node.js 的 async/await 功能结合使用。当调用我的函数 printEmployees
时,我想保存由 orderEmployees
函数查询的员工列表。而 orderEmployees
中的 console.log
语句返回预期的查询,printEmployees
中的 console.log
返回undefined
,提示我没有正确返回promise。
我完全不熟悉 promise ,以至于我没有正确理解范式......非常感谢任何帮助。
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';
});
},
最佳答案
为了使 orderEmployees
表现得像异步函数,您必须返回结果 promise 。使用没有 async/await
关键字的 Promise 时要遵循两条规则:
- 如果函数返回
Promise
,则该函数是异步的
- 如果您有一个 promise (例如由异步函数返回),则必须对其调用
.then
或将其返回。
当您使用 async/await
时,您必须 await
在您获得的 promise 上。
这表示你会注意到你没有返回 orderEmployees
中生成的 promise 。很容易修复,但也很容易将该函数重写为异步。
orderEmployees: (companyID) => {
return User.find({company:companyID}) // Notice the return here
.exec()
.then((employees) => {
// FIRST CONSOLE.LOG
console.log(employees);
return employees;
})
.catch((err) => {
return 'error occured';
});
},
或
orderEmployees: async(companyID) => {
try {
const employees = await User.find({company:companyID}).exec();
console.log(employees);
return employees;
} catch (err) {
return 'error occured';
}
},
PS:这里的错误处理有些缺陷。我们通常不会通过从函数返回错误字符串来处理错误。在这种情况下,最好让错误传播,并从一些顶级 UI 代码中处理它。
关于javascript - 使用带有 async/await 的 mongoose promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46457071/