node.js - 如何在 Node js 中从服务返回两个以上的值

标签 node.js express sequelize.js

我有一个 Controller /user.js 文件,可以使用 service/user.js 中的函数获取数据
从服务中的 getUsers 函数我不能返回超过 1 个值。例如我想返回 return{User,pages} 。但是,我在像 return{User,pages} 一样返回时出错
以下是我在使用 return{User,pages} 时遇到的错误

userService.getUsers(...).then is not a function



Controller /user.js
function getUsers(req, res){
    userService.getUsers({
         page_no:req.body.page_no,
         previous:req.body.previous
    }  
    )
    .then(data => res.send(data));
};

服务/user.js
const getUsers = function (data) { 
    let limit = 10;   // number of records per page
    let offset = 0;
    let page = data.page_no;      // page number
     data = Users.findAll({where: {
        DeletedAt: {
          $eq: null
        }
    }})
    const pages = Math.ceil(data.count / limit);
        offset = limit * (page - 1);
    const User =  Users.findAll({
        attributes: ['id', 'first_name', 'last_name', 'role_id','login','is_active'],
        limit: limit,
        order: [
                ['createdAt', 'DESC']
            ],
        offset: offset,
        $sort: { id: 1 },
        where: {
            DeletedAt: {
              $eq: null
            }
        }
    })
    return User
    };

最佳答案

看起来您正在使用一些返回 Promise 的 ORM。

当您只返回 User 时, User 的类型(可能,因为您没有收到错误)是 Promise ,因此该函数将返回一个 promise ,您可以调用 .then 方法。

但是,当您返回 { User, pages } 时,您返回的不是 promise 而是 Object 并且对象没有 then 方法,这就是您收到错误的原因。

当您返回对象 { User, pages } 时,您可以更改代码以提取 promise 并对其调用 then 方法:

function getUsers(req, res){
  const { User, pages } = userService.getUsers({
    page_no:req.body.page_no,
    previous:req.body.previous
  })
  // Call the then User which is a Promise
  User.then(data => res.send(data))
};

关于node.js - 如何在 Node js 中从服务返回两个以上的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56163101/

相关文章:

node.js - 为什么我无法安装特定版本的 npm 以及如何安装?

javascript - 如何确定 Stripe webhook 'invoice.payment_failed' 是从 Stripe 操作还是用户操作调用的?

javascript - 数组在拼接后不会改变它的数据。范围问题?

node.js - 无法连接到 EC2 上的 Postgres : ECONNREFUSED

sequelize.js - 如何在 LEFT JOIN 中嵌套 INNER JOIN

node.js - 在 windows 中使用 uglifyjs 和 nodejs

angularjs - nodejs 表达并使用 https

node.js - 将 Express React Redux 模板部署到 Heroku 的步骤

node.js - Promise 无法解析 express 中间件中的异步函数内部

node.js - LOCK 在sequelize -> types/transaction.d.ts 中定义为ENUM 和接口(interface)