use*_*157 3 node.js promise express sequelize.js
对 Javascript 和 Node.js 来说是全新的。我正在尝试开始使用 Sequelize 作为 ORM 并做了一个简单的查询
var employeeList = Employee.findAll().then(function(result){
console.log(result.length);
console.log(result[0].employeeName);
//how do I return this to a variable with which I can do further processing
return result;
});
//do something with employeeList
employeeList[0].employeeName //cannot read property of undefined
Run Code Online (Sandbox Code Playgroud)
虽然控制台日志打印出正确的名字,但employeeList 本身不包含任何数据。我尝试打印employeeList,它显示了承诺
Promise {
_bitField: 0,
_fulfillmentHandler0: undefined,
_rejectionHandler0: undefined,
_promise0: undefined,
_receiver0: undefined }
Run Code Online (Sandbox Code Playgroud)
我确实浏览了 promise 的概念,但无法得到一个关于如何将 promise 的结果返回到函数外部变量的东方示例。我认为返回结果可以解决问题。我在这里错过了什么吗?我可以理解我可以在 promise 函数中处理结果。如果场景是进行两次数据库调用,然后处理两次调用的结果以返回合并结果,那么如何在不将结果传递给变量的情况下完成此操作。
小智 5
因此,根据您关于使用独立查询的评论的帖子,我想向您展示如何正确使用它们:
//Each request in it's own function to respect the single responsability principle
function getAllEmployees() {
return Employee
.findAll()
.then(function(employees){
//do some parsing/editing
//this then is not required if you don't want to change anything
return employees;
});
}
function doAnotherJob() {
return YourModel
.findAll()
.then(function(response) => {
//do some parsing/editing
//this then is not required if you don't want to change anything
return response;
});
}
function do2IndependentCalls() {
return Promise.all([
getAllEmployees(),
doAnotherJob()
]).then(([employees, secondRequest]) => {
//do the functionality you need
})
}Run Code Online (Sandbox Code Playgroud)