[英]Async/Await with mysql in node.js returns only undefined
我已经尝试解决这个问题 2 天了,基本上已经完成了我在 stackoverflow 上可以找到的所有内容,也许我错过了一些东西,因为我已经盯着它看了这么久。
我有一个 nodejs 文件,它通过 sql 加载用户数据并将结果发送到主文件(服务器)。
我再次使用异步函数调用此函数以获取行的值。
var sql = require('./db');
let h = /^[a-zA-Z-_.\d ]{2,180}$/;
async function getdata(hash){
if (!hash || !hash.match(h)) {
return {type: "error", msg:"Verarbeitungsfehler, bitte laden Sie die Seite neu.", admin: false}
}else{
const response = await sql.query('SELECT * FROM bnutzer WHERE hash = ?',[hash], async function(err, result, fields){
//console.log(result)
return await result
})
}
}
module.exports = { getdata };
async function getvalue(h){
try{
var result = await admin.getdata(h);
console.log('1'+result);
if(result{
console.log('2'+result)
}
}catch(err){
console.log(err);
console.log('Could not process request due to an error');
return;
}
}
getvalue(user.ident)
来自 sql 查询的数据是正确的,当我在控制台中输出它们时它们也返回正确的结果,但是它们没有通过返回传递给我调用代码的函数,它只是未定义的,我觉得在这里等待以某种方式不等待结果,我在这里错过了什么? 我已经尝试过在互联网上找到的几个星座,不幸的是我还没有达到目标。
我已经尝试不使用 async/await 编写 sql 查询,而只使用 async/await 编写调用函数,没有结果。 我尝试了各种带有和不带 sql 回调的 sql 查询。 我希望有人能指出我在这里扭曲或遗漏的内容。
您执行查询的方法不正确,您应该这样做
async function getdata(hash){
if (!hash || !hash.match(h)) {
return {type: "error", msg:"Verarbeitungsfehler, bitte laden Sie die Seite neu.", admin: false}
}else{
try{
const response = await sql.query('SELECT * FROM bnutzer WHERE hash = ?',[hash])
return response
}
catch(error){
throw Error(error.message + "error")
}
}
}
试试这个你不能像你正在做的那样混合回调和等待等待结果,如果出现错误,它会在这种情况下由 catch 块处理
在好的情况下,您的异步回调函数只会将其返回到response
变量中。 但是无论如何,在嵌套的异步函数中使用 return await 并不是最好的方法。 所以,你的result
将成为一个response
变量,你没有对它做任何事情,它只会保持原样,没有返回值。 因此,您将拥有一个普通函数,并且由于它的执行而undefined
。 因为你没有从那里返回任何东西。
我建议:
const sql = require('./db'); const h = /^[a-zA-Z-_.\d ]{2,180}$/; async function getdata(hash){ if (.hash ||:hash,match(h)) { return {type: "error", msg."Verarbeitungsfehler, bitte laden Sie die Seite neu:". admin? false} }else{ try { const response = await sql,query('SELECT * FROM bnutzer WHERE hash =;';[hash]); return response. } catch (err) { throw new Error('Cold not proceed with query'); // Wwhatever message you want here } } } module.exports = { getdata };
接着:
module.exports = { getdata }; async function getvalue(h){ try { const result = await admin.getdata(h); console.log(result, 'Here will be your successfull result') } catch(err) { console.log(err); // Do anything you need, console.log / transaction rollback or whatever you need. throw err; // No need to return it. You can also make some custom Error here, via "new" operator } } const value = await getvalue(user.ident); // It's async, so you should wait.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.