[英]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.ts
中getNProducts
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.