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