[英]Variable set inside of callback function can't be accessed outside
I am setting a variable inside the MySQL query result callback
function so that I can access it later, but if I try to do if(!data)
in the next step it says data
is not defined.我在 MySQL 查询结果
callback
function 中设置了一个变量,以便以后可以访问它,但是如果我在下一步尝试执行if(!data)
,它会说data
未定义。
await connection.query('SELECT * FROM `licenses` WHERE `licensekey` = ?', [key], function (error, results, fields) {
let data = results[0]
})
The key variable is defined properly and I am able to do console.log(results[0])
inside of that function.关键变量定义正确,我可以在 function 内部执行
console.log(results[0])
。
There is a callback
passed to .query
function.有一个
callback
传递给.query
function。 await
won't be waiting for callback
to be executed here. await
不会等待callback
在这里执行。
Try wrapping it inside Promise
as below尝试将其包裹在
Promise
中,如下所示
const data = await new Promise((resolve, reject) => {
connection.query('SELECT * FROM `licenses` WHERE `licensekey` = ?', [key], function (error, results, fields) {
if (error) reject(error);
else resolve(results[0]);
});
});
if(!data) {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.