繁体   English   中英

查询响应值从我的 model 传递到我的 controller?

[英]Query response value getting passed from my model to my controller?

我正在使用 mysql db 构建节点 js 服务器。 I am getting the proper response from my db, but my model is not properly sending the response to my controller, or my controller is not waiting for the async function to finish. 我的 controller 文件中的响应返回为未定义。 这是我的代码:

Model:

const sqlDb = require('../../db/index.ts');

module.exports = {
  getNProducts: (page = 0, n = 5) => {
      let offset = page * n;
      if (offset > 0) {
        sqlDb.query(`SELECT * FROM Products ORDER BY id DESC LIMIT ${n}, ${offset}`, (err, res, feilds) => {
            if (err) {
                return;
            } else {
                return res;
            }
        });
        } else {
        sqlDb.query(`SELECT * FROM Products ORDER BY id DESC LIMIT ${n}`, (err, res, feilds) => {
            if (err) {
                console.log(err);
                return;
            } else {
                return res;
            };
          });
        }
  }
}

Controller:

 const productModel = require('../models/productModel.ts');
    
    module.exports = {
        getProducts: async(req, res) => {
          let response = await productModel.getNProducts();
          res.send(response).status(200);
        }
    }

productModel.tsgetNProducts function 不是异步 function 所以它不会返回 promise

我推荐这个,这是我见过的最清晰的方式来解释什么是异步等待https://www.w3schools.com/js/js_async.asp

实际发生的是在 controller 中
let response = await productModel.getNProducts();

不等待 promise 解决,因为productModel.getNProducts()不返回是异步 function (不返回承诺)

你可以编辑getNProducts看起来像这样

getNProducts: async (page = 0, n = 5) => { // now this return a promise
  let offset = page * n;
  if (offset > 0) {
   await sqlDb.query(`SELECT * FROM Products ORDER BY id DESC LIMIT ${n}, ${offset}`, (err, res, feilds) => {// and now you await for it here
        if (err) {
            return;
        } else {
            return res;
        }
    });
    } else {
   await sqlDb.query(`SELECT * FROM Products ORDER BY id DESC LIMIT ${n}`, (err, res, feilds) => { // and here too
        if (err) {
            console.log(err);
            return;
        } else {
            return res;
        };
      });
    }

}

sqlDb.query()中的getNProducts() () 调用使用回调方法,实际上没有返回 promise。 您可以尝试重写您的getNProducts() function 以返回 promise 像这样。

module.exports = {
  getNProducts: (page = 0, n = 5) => {
    const offset = page * n;
    const limitString = (offset > 0)  ? `LIMIT ${n}, ${offset}` : `LIMIT ${n}`;
    return new Promise((resolve, reject) => {
      sqlDb.query(`SELECT * FROM Products ORDER BY id DESC ${limitString}`, (err, res, feilds) => {
          if (err) {
              reject(err);
          } else {
              resolve(res);
          }
      });
    });
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM