How can I use javascript async / await?

13

I saw that it is now possible to use the async and await keywords in javascript, but how does this actually work?

    
asked by anonymous 09.06.2017 / 00:00

2 answers

10

Asynchronous Functions

First of all, we need to mention that these keywords are part of ES2017 (ECMA- 262) ).

Let's go by parts, first about async . When declaring an async function , you will be, as the name already says, declaring an asynchronous function, which returns an object AsyncFunction .

To understand the purpose of this feature first of all you will need to understand, if you do not already know, what are Promises , an already known resource of the Javascript community for a few years. Here's a quick explanation:

Promises

Promise is an object used for asynchronous processing. A Promise ("Promise") represents a value that may be available now, in the future or never.

Upon receiving the promise object, it may be in the pending, realized, rejected, or established states. In other words, you may have an object in hands that will soon have a value, but you currently do not have it, you only have the promise that at some point this value will be filled , or not, if something goes wrong thing on the way.

Now that we know about promises, and that they already work asynchronously, what is the purpose of async functions? Here's an example of a promise:

function pegarDadosProcessados(url) {
    return baixarDados(url) // retorna uma Promise
        .catch(e => {
            return baixarDadosReservas(url) // retorna uma Promise
        })
        .then(v => {
            return processarDadosNoWorker(v); // retorna uma Promise
        });
}

Being quite succinct about the explanation, this code snippet is basically a function that returns a promise and inside it, we have processes that need to be executed in a certain order, so we need to download baixarDados(url) and then using the promise then run processarDadosNoWorker(v) .

Now let's look at all this using asynchronous functions or async functions .

Using Asynchronous Functions

The idea of async / await functions is to simplify the use of Promises synchronously and perform some procedures in a Promises group. Just like Promises are similar to structured callbacks, async / await functions are similar to generators' join with Promises.

For this whole story to get clearer let's redo the previous function using async / await:

async function pegarDadosProcessados(url) {
    let v;
    try {
        v = await baixarDados(url); 
    } catch(e) {
        v = await baixarDadosReservas(url);
    }
    return processarDadosNoWorker(v);
}

Note that in the above example there is no await statement in the return statement, because the return value of an async function is implicitly passed by a Promise.resolve .

Conclusion

To conclude async is used to perform functions asynchronously, that is, functions that take time and prevent the main process from continuing. A clear example of this situation would be a query to the server, this may take minutes depending on the person's internet connection, if this were done synchronously everything would be left waiting for the server response, an asynchronous function would be ideal for this. / p>

While await is used within the asynchronous functions to pause the execution of the same in order to wait for a certain function to be executed before continuing its processing.

    
09.06.2017 / 02:02
6

What is async/await ?

The async / await is the third and most modern way of working with asynchronous functions.

This new type of functionality, released in the ES2017 (ES7) , brings you to JavaScript is the first truly asynchronous function and is another tool for working asynchronous processes like Promises and callbacks . / p>

Interestingly, the async / await syntax is the closest to sequential (non-asynchronous) code, since it allows you to write the code stream sequentially, and the async function tries to "pause" execution until you have a answer to give.

How to use?

Simple, two rules:

  • Using async before the word function in the statement of the function that has await in your body / content / inner. >

  • using await before the invocation of a function (function name) that returns a promise, within a async function . >

One thing to keep in mind is that async function always returns a Promise, so we use .then to get the response of a async function .

Example with 2 variants:

  • One with async / await, more readable and sequential
  • One with Promises chaining

// esta função dá "sinal verde" com x segundos de atrasado
function atrasarSegundos(delay) {
  return new Promise(
    (res, rej) => setTimeout(() => res(delay), delay * 1000)
  );
}

// este é o meu pipeline com async/await
async function meuPipeline() {
  var espera = 0;
  espera += await atrasarSegundos(1);
  espera += await atrasarSegundos(1);
  espera += await atrasarSegundos(2);
  espera += await atrasarSegundos(1);
  return 'Via await depois de ' + espera + ' segundos e 4 chamadas async';
}
meuPipeline().then(
  frase => console.log(frase)
);

// usando somente Promises 
var espera = 0; // tem de ficar fora da promise
var viaAPromise = atrasarSegundos(1).then(delay => {
  espera += delay;
  return atrasarSegundos(2);
}).then(delay => {
  espera += delay;
  return atrasarSegundos(1);
}).then(delay => {
  espera += delay;
  return atrasarSegundos(1);
}).then(delay => {
  espera += delay;
  console.log('Via await depois de ' + espera + ' segundos e 4 Promises');
});
    
09.06.2017 / 07:37