【发布时间】:2021-02-03 15:32:34
【问题描述】:
我有一个节点文件从另一个模块页面请求返回变量。所有数据函数“工作”,但“返回查询”没有将查询值发送回我的初始请求,并且我的 existingUser 变量未定义。在控制台日志检查中,我将现有用户显示在查询之一之前。这就像等待请求被忽略了。
任何帮助表示赞赏......我是这一切的新手!
请求页面 -
const sqlRequests1 = require('./sqlAdmin/sqlRequests1');
.
.
.
app.post('/', async (req, res) => {
const { club, first_name, last_name, email, tel, address, post_code, password, passwordConfirmation} = req.body;
let existingUser = await new sqlRequests1.Queries('contact',email).getAll();
console.log(`existingUser is ${existingUser}`); //THIS CONSOLE LOG RETURNS "undefined"
if (existingUser) {
return res.send('Email in use');
}
if (password !== passwordConfirmation) {
return res.send('Passwords must match');
}
res.send('Account created!!!');
});
模块页面 - sqlRequests1
class Queries {
constructor(table, selection) {
this.table = table;
this.selection = selection;
console.log(selection); //THIS DATA CHECK WORKS
if(!table) {
throw new Error('Need a table to connect to');
};
};
getAll() {
//Confirm if the emasil exists - if it does then give error message
let q = 'SELECT * FROM ?? ';
connection.query(q, this.table, function (error, results,fields) {
if (error) throw error;
const query = (results[0].email);
console.log(`query is ${query}`); //THIS PROVIDES THE CORRECT DATA
return query; //THIS RETURN IS NOT GETTING BACK TO existingUser variable?
});
};
};
module.exports.Queries = Queries;
【问题讨论】:
-
以下帖子显示了有关如何处理这种情况的一些建议:stackoverflow.com/questions/18361930/…恕我直言,第二个答案(不是公认的答案)提供了处理代码的最干净和最清晰的方法。
标签: node.js node-modules return-value