javascript - Promise 在 Node module.exports 中返回未定义

标签 javascript node.js express promise

尝试在 routes.js 中登录时,Promise 返回 undefined,但在 queries.js 中登录时工作正常。我应该如何更改 promise 以正确返回对 routes.js 的响应?

queries.js中:

const rsClient = require('./client.js');

const query = {
    one: 'SELECT * FROM my.db'
}

module.exports = {
    rsProdRecs: (req, res) => {
         rsClient.query(query.one)
            .then(res => {
                return res;
            })
            .catch(err => console.log(err));
    }
};

routes.js

var express = require('express');
var router = express.Router();
var queries = require('../queries');

router.get('/', function(req, res, next) {
  const data = queries.rsProdRecs();
  console.log(data)
  res.send(data);
});

module.exports = router;

最佳答案

您的代码存在一些问题。第一个问题已经被其他用户指出,您需要从 rsProdRecs 返回 promise 。 thencatch block 以及您如何在路由中使用该方法也存在问题,如下面的代码所述:

module.exports = {
    rsProdRecs: (req, res) => {
        return rsClient.query(query.one);

        // This is redundant, you're not transforming res in any way so this can be omitted.
        // .then(res => {
        //     return res;
        // })

        // This will cause the promise to return 'undefined' if rsClient.query(...) rejects,
        // instead error handling should be done in the calling function.
        // .catch(err => console.log(err));
    }
};

您可以重构您的路线以正确使用您的 Promise 返回方法:

router.get('/', function (req, res, next) {
    // We cannot consume the "data" directly, we must wait for the promise to resolve.
    queries.rsProdRecs()
        .then((data) => {
            console.log(data);
            res.send(data);
        })
        .catch((err) => {
            console.log(err);
            res.status(500); // insert correct error response here
        });

});

或者使用async/await,因为您已经在使用 ES6 功能:

router.get('/', async function (req, res, next) {
    try {
        const data = await queries.rsProdRecs();
        console.log(data);
        res.send(data);
    } catch (e) {
        console.log(err);
        res.status(500);
    }
});

关于javascript - Promise 在 Node module.exports 中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54795893/

相关文章:

node.js - Express session 和 PassportJS 之间的区别

node.js - Node.js 的 Express 是否有 .request()

javascript - 我应该如何向其他本地服务器发出请求?

javascript - 使用 2 个数组输入 x-y 进行绘图

javascript - Angular Material 数据表显示 [object Object]

node.js - Mongoose - 使用 .populate 访问嵌套对象

node.js - 如何修复 "WARNING: The ` useMongoClient` 选项在 mongoose 5.x 中不再需要,请删除它。”

javascript - jQuery:如何将 `map` 与 jQuery 中的类一起使用

javascript - 为什么对对象的引用被其值替换

javascript - Node控制台如何显示 float