简体   繁体   中英

Query response value getting passed from my model to my controller?

I am building a node js server with a mysql db. 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. response in my controller file comes back as undefined. Here is my code:

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

in the productModel.ts the getNProducts function is not an async function so it doesn't return a promise

I recommend This, it is the clearest way I have ever seen to explain what is async await https://www.w3schools.com/js/js_async.asp

What is actually happening is in the controller the
let response = await productModel.getNProducts();

doesn't await a promise to resolve because productModel.getNProducts() doesn't return is an async function (doesn't return a promise)

you could edit the getNProducts to look like this

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

}

The sqlDb.query() calls inside your getNProducts() function use a callback method and is actually not returning a promise. You can try rewriting your getNProducts() function to return a promise like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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