async function getResult(){
let connection;
try {
connection = await mysql.createConnection(dbConfig);
const result = await connection.query('select height from users where pin=1100');
console.log(result[0].height);
return result[0].height;
} finally {
if (connection && connection.end) connection.end();
}
}
Corrige os seguintes problemas:
- Se você pode usar async/await, é inútil ainda usar
thenpara essas situações. - Você não precisa de JSON
stringifyeparsese você estiver registrando algo. - Se você detectar um erro ao fechar uma conexão, você realmente deve relançar para que a função que chama
getResultnão recebe lixo/undefinedde volta. Em vez de relançá-lo, acabei de adicionar umfinallybloco que sempre fecha a conexão, seja ela bem-sucedida ou não. - Como você está usando async/await, seu mecanismo javascript deve ser compatível com
leteconst. É melhor quevar=) - Você não estava retornando nada.