简体   繁体   English

回调 function 内部的变量集无法在外部访问

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM