Async/Await x Sync

Asked

Viewed 763 times

2

I’m studying synchronous/asynchronous behaviors at the angle and I’m not sure when to use async and await....

Correct me if I’m wrong...

I understand that for me to call with await, the return has to be Promise and therefore I will be waiting for this promise of return to my async method.

But if I have to wait for the answer, why use async with await, and if I use the method without async I also expect an answer?

I know there’s a reason, but I can’t see it...

  • 1

    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 the await 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.

  • @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)

  • See first comment.

  • 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)

  • 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 ??

  • 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

  • If you get the conclusion, from the first link you sent me, I understood as being the opposite of what Voce explained here

  • 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 the await waiting is blocking, you can’t do anything else while waiting.

  • 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...

  • 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...

  • 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.

  • 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?

Show 8 more comments

2 answers

2


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

  • It turned out that in the comments of my question the focus was on the async/await when in fact it was both vs Sync... Anyway, both Charlie and Anderson told me one thing I didn’t know is exactly what I tried to summarize in my last comment on my question... But your answer cleared the doubts I had and I appreciate your help :)

  • vlw @Leohenrique qqr thing is just talk ;)

1

It doesn’t make much sense to compare synchronous and asyncronous methods since they have different purposes. think like this imagine that you want to make a cake if you already have all the igredientes Oce can just run the method to make Cake() and wait for your cake ready, this would be the synchronous case. Now imagine that you don’t have the igredientes and you ask your friend to go to the market to buy. If you run to do Shop() it will have the null igredientes and it will not work. If you wait for your friend to come back it will be inefficient because you don’t know how long it will take to come back, so if you use the await that basically means when he comes back with the igredientes (usually an http return in real life) then you can make the cake. I don’t know if it was the best metaphor but I hope you understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.