我是这个节点js的新手并经历了许多解释,尝试了很多解决方案,但仍然无法让我的脑袋缠绕在函数回调上。
//app.js file
var dashboardfunc = require('./models/admindashboard');
app.get("/dashboard/:id?", function(req, res) {
console.log("we are here in dashboard")
var data = {id: req.params.id};
console.log(data)
dashboardfunc.productlist().then(function(results){
console.log("i am here now ....")
console.log(results)
}).catch(function(err){
if(err){
console.log(err)
}
})
});
//admindashboard.js file
//I tried many other alterations like using call back etc.
// i want the damn results to be back to the app.js and use that
//
function productlist(data) {
return new Promise(function(resolve, reject) {
var param = [data.id];
var sql = 'select * from product where seller_id=?';
console.log(param)
pool.query(sql, param, function(err, results) {
if (err) {
console.log(err)
}
else {
if (results === undefined) {
reject(new Error("Error rows is undefined"));
}
else {
console.log("we got here in productlist")
console.log(results)
return results;
}
}
})
})
}
module.exports = productlist;
< - 结果 - > Rb-v2开始!!!我们在仪表板{id:'23'} TypeError:dashboardfunc.productlist不是函数
问题是为什么很难得到结果,以及为什么调用函数需要如此复杂,获得返回数据。随之而来的是回调v / s承诺的协议(是的,我读了几乎所有的帖子仍然是我天真的大脑不能处理它)
尝试这些小修补程序开始:
admindashboard.js
导出唯一的函数,但app.js
尝试将它用作对象的属性。您需要这种类型的导出:module.exports = { productlist };
或者这个使用:
dashboardfunc().then
dashboardfunc(data).then
而不是提到dashboardfunc.productlist().then
。resolve
函数中不使用productlist()
回调。用它来从promise中返回数据:resolve(results);
而不是return results;
。 if (err) {
reject(err)
}
else {
if (results === undefined) {
reject(new Error("Error rows is undefined"));
}
代替:
if (err) {
console.log(err)
}
else {
if (results === undefined) {
reject(new Error("Error rows is undefined"));
}