5
I thought I understood how asynchronous function works with await
. In my understanding the await
was waiting for the resolve
of Promise
to continue to the following.
To test this operation, I created two functions that return a promise and included a timer (simulating database access). I noticed that the code was executed asynchronously, ignoring the await
.
function getSenha() {
return new Promise(function(resolve, reject) {
setTimeout( function() {
console.log( 'Executa uma vez após 9 segundos.' );
}, 9000 );
resolve("RET_SENHA");
});
};
function getMensagem() {
return new Promise((resolve, reject) =>{
setTimeout( function() {
console.log( 'Executa uma vez após 1 segundo.' );
}, 1000 );
resolve("RET_MSG");
});
}
async function montaMensagem() {
const senha = await getSenha();
const msg = await getMensagem();
console.log('Senha: ', senha);
console.log('Mensagem: ', msg);
}
montaMensagem();
Follow the result:
Senha: RET_SENHA
Mensagem: RET_MSG
Executa uma vez após 1 segundo.
Executa uma vez após 9 segundos.
The right thing wouldn’t be:
Executa uma vez após 9 segundos.
Executa uma vez após 1 segundo.
Senha: RET_SENHA
Mensagem: RET_MSG
With the consultation at the Bank:
getSenha() {
return new Promise((resolve, reject)=> {
let connection = AtendimentoDB.connect();
let sql = "select * from senha";
connection.query(sql, function (error, results, fields) {
if (error) {
reject(error);
} else {
resolve(results);
}
});
connection.end();
});
};
getMensagem() {
return new Promise((resolve, reject) =>{
let connection = AtendimentoDB.connect();
let sql = "SELECT mensagem FROM configuracao;";
connection.query(sql, function (error, results, fields) {
if (error) {
reject(error);
} else {
resolve(results);
}
});
connection.end();
});
};
async function montaMensagem() {
const senha = await getSenha();
const msg = await getMensagem();
console.log('Senha: ', senha);
console.log('Mensagem: ', msg);
}
try to put async in getMensage() and getNo()
– OtavioCapel
@Otaviocapel, thanks for the tip, but it didn’t work. From what I understand, only the function that will use the await needs to be async, I’m sure?
– Developer
Don’t you need to put the solutions within the timeout? It actually runs the Function of the timeout after a certain period, but at how much this, it keeps running the code (in case it solves it)
– Leonardo Buta
I did the test here by placing the resolve within the timeout and in fact there was the expected result, would be this?
– Leonardo Buta
It would not be right to put the "resolve("RET_SENHA")" within the timeout Function?
– Leonardo Buta
@Leonardobuta, you’re right. The correct thing would be to include within the setTimeout. Thanks for the return.
– Developer