But if I have to wait for the answer, why use async with
await, being that if I use the method without the async I also hope
an answer?
I believe this is not your question but responding to the letter, to use the await
it is necessary that it is within a function async
.
Now what I think is your question with a slightly more complete answer: Javascript is a synchronous language but it provides us with some mechanics to have an asynchronous behavior. One of the ways is through the callbacks, where we pass a function as parameter of a method and it is executed at a given instant without "locking" the execution of its code and consequently without locking the interface.
As the code grows, we will have a lot of callbacks and it becomes a mess and then comes the term "callback Hell". With evolution came the Promise
who helped organize these callbacks. Then came the async/await
which is an extension of Promises to simplify its use.
So if I understand your doubt correctly, if you expect a response from a function already knowing that your return is a Promise
, to use the await
execution is required to be within an asynchronous function (decorated with async
), otherwise you should use the then/catch
to pick up the answer/error. If the function does not return a Promise its use will "lock" the execution of the rest of the code until it is finished. See the big difference between running a synchronous function vs a async/await
is that the first locks the whole code while the second only locks inside the function to which it belongs not impacting on the execution of the rest of the code.
See the code below:
function retornaPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('DentroPromise');
resolve('PromiseFinalizada');
}, 2000);
});
}
// Com o async
async function minhaFuncaoAsync() {
// Aqui o código espera a Promise antes de prosseguir com o restante do código DESTA função.
// Isso porque estamos usando o await logo na primeira linha.
// A diferença entre este caso e uma execução síncrona, é que
// a síncrona travaria a execução das outras funções até a sua resolução
console.log(await retornaPromise());
console.log('Fim-minhaFuncaoAsync');
}
// Com o async
async function minhaFuncaoAsync2() {
const asyncFunc = retornaPromise();
console.log('Fim-minhaFuncaoAsync2');
console.log(await asyncFunc);
}
// Sem o async
function minhaFuncao() {
// O conteúdo dentro do then será executado
// quando a Promise for resolvida mas o restante de código
// desta função será executado independente da Promise
retornaPromise().then(a => console.log(a));
console.log('Fim-minhaFuncao');
}
// Veja que uma função não interfere na execução da outra
minhaFuncaoAsync();
// Se aqui neste trecho houvesse um processamento síncrono, o código ficaria travado aqui até o término de sua execução.
minhaFuncaoAsync2();
minhaFuncao();
/*
Resultado console:
Fim-minhaFuncaoAsync2
Fim-minhaFuncao
(2s depois)
DentroPromise
PromiseFinalizada
Fim-minhaFuncaoAsync
DentroPromise
PromiseFinalizada
DentroPromise
PromiseFinalizada
*/
I hope I have clarified your doubts, otherwise please provide more details so that others can help ;)
abs
In a very well summarized way: with the
await
you wait for the answer, but release the processor to perform other functions in the meantime and return to execute that code when you have the answer. Without theawait
you force the processor to wait with you, even if it has nothing to do waiting. That’s the principle of coroutines, if you want to research more.– Woss
And others: How to really learn how to use javascript promises? / When using async and Defer, the order of the scripts is respected?
– Woss
@Andersoncarloswoss, that I even understand, but my question is about using async and await and not a synchronous method, pq I would use async with await being q if I only use Sync I would have the same result (?!?! ) (I don’t know, I’m trying to understand this)
– LeoHenrique
See first comment.
– Woss
If I have to use await to force an answer, why don’t I just use Sync straight? (in case when I speak Sync would be the method/function without async in the beginning)
– LeoHenrique
That would be the difference:
mas libera o processador para executar outras funções enquanto isso e volta a executar aquele código quando possuir a resposta
??– LeoHenrique
I think you were wrong at some point to explain there in the first comment, because first you say that with the await I wait for the answer and without the await I force.... is that right ?! is not clear to me
– LeoHenrique
If you get the conclusion, from the first link you sent me, I understood as being the opposite of what Voce explained here
– LeoHenrique
Then you must have misinterpreted it. In both ways you will await the answer, the difference is that using the
await
you do not block the process of continuing. For example, you can still handle the click on a button on the screen even while waiting for the server response. Without theawait
waiting is blocking, you can’t do anything else while waiting.– Woss
as it is being said in the conclusion of this comment: https://answall.com/a/211526/104028, this being contradictory to what Victor is telling me and this is confusing me...
– LeoHenrique
I have already done some tests in my application with this, I have 3 screens, in the third screen I need a filled information, therefore I use the async on screen 1 without await and the processing continues, step by screen 1, 2, 3 and have the data filled, In test 2 was to put the await in this async and I could not leave screen 1 until I got the return .... So in a test carried out, what you tell me this contradicting, before what I could see in my tests...
– LeoHenrique
Leo, understand that "pausing the execution of the function" is not the same as blocking the process. If in the function you display the result of the request to the server, you need to ensure that you get this result. The
await
gives you that assurance, he pauses the function until you get the return, but all the rest of the project can continue running.– Woss
Now I can visualize, I will summarize the q I understood: using Sync, I hold the "user" to that process, roughly, to that screen... using async with await, I lock the function/method where it is, but the app flow continues, is +/- that?
– LeoHenrique