这是我的函数:
static async isExiste (email: string) {
const bdd = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_DATABASE,
socketPath: process.env.SOCKETPATH,
port: parseInt((process.env.PORTMYSQL === undefined) ? '3306' : process.env.PORTMYSQL)
})
const emailExist = `SELECT 1 FROM user WHERE email='${email}'`
let bool = false
await bdd.query(emailExist, (err, result) => {
if(result[0]) {
bool = true
console.log(bool)
} else {
bool = false
console.log(bool)
}
})
console.log('boolean renvoyé: ', bool)
return bool
}
这是控制台的回归:
boolean renvoyé: false
true
当函数的返回值应该为true时,它是false。我不明白为什么sql请求没有阻止脚本。
bdd.query()
不返回promise,并且console.log()
和return语句在查询回调之外,这意味着它们发生在调用回调之前。您可以通过返回promise,然后用您的返回值解析promise来解决此问题。修改代码使其看起来像这样应该可以工作:
static isExiste (email: string) {
return new Promise((resolve, reject) => {
const bdd = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_DATABASE,
socketPath: process.env.SOCKETPATH,
port: parseInt((process.env.PORTMYSQL === undefined) ? '3306' : process.env.PORTMYSQL)
})
const emailExist = `SELECT 1 FROM user WHERE email='${email}'`
bdd.query(emailExist, (err, result) => {
if (err) {
reject(err);
return;
}
const bool = !!result[0];
console.log('boolean renvoyé: ', bool)
resolve(bool)
})
});
}