NodeJS Sequelize从查询返回数据

时间:2018-03-30 17:57:28

标签: node.js express promise sequelize.js

Javascript和Node的全新内容。我试图开始使用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 

当控制台日志打印出正确的名称时,employeeList本身不包含任何数据。我尝试打印employeeList并显示承诺

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

我确实略过了承诺概念,但无法得到一个东方例子,说明如何将承诺的结果返回到函数外部的变量。我认为返回结果会成功。我在这里错过了什么吗?我可以理解我可以在promise函数中处理结果。如果场景是进行两次数据库调用,然后处理两次调用的结果以返回合并结果,那么如何在不将结果传递给变量的情况下完成。

3 个答案:

答案 0 :(得分:4)

因此,根据您对使用独立查询的评论的帖子,我想向您展示如何正确使用它们:



//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
  })
}




答案 1 :(得分:2)

另一种方法是使用 async await

async function getEmployees(){
    var employeeList = await Employee.findAll().then(function(result){
        console.log(result.length);
        console.log(result[0].employeeName);
        return result;
    });

    employeeList[0].employeeName;
}

答案 2 :(得分:1)

then方法返回Promise,而不是您的员工列表。

如果您想使用员工列表,您应该在传递给现有then电话的功能或后续then电话中执行此操作,如下所示。

Employee
  .findAll()
  .then(function(el){
    console.log(el.length);
    console.log(el[0].employeeName);
    return el;
   })
  .then(function(employeeList){
    //do something with employeeList
    employeeList[0].employeeName
   });