作为员工应用程序管理的一部分,我希望将业务逻辑数据库操作与我的主应用程序文件分开。 最简单的操作是使用async/await从数据库中读取所有员工进行同步:
module.exports.getEmployees = async () => {
const employees = await Employee.find();
return employees;
}
在我的 app.js 中,我输入了以下代码:
const employee = require(__dirname + "/models/employee.js");
app.get("/employees", (req, res) => {
const employeeList = employee.getEmployees();
employeeList.then(res.send(employeeList));
})
但是数组仍然显示为空?
最佳答案
Promise 中的
then
子句接受函数作为参数,并且该函数有一个保存实际响应的参数。
类似这样的东西 -
new Promise().then((response) => {
console.log(response);
});
您正在执行 employeeList.then(res.send(employeeList));
这意味着 then 子句的参数是 res.send()
,这将不起作用.
试试这个 -
employeeList.then((list) => {
// please note the response type here depends on the Content-Type set in the response Header
res.send(list);
// In case of normal http server, try this -
res.send(JSON.stringify(list));
});
我希望这会有所帮助。
关于javascript - 无法同步 Mongoose 操作以返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60682560/