How can I use javascript async/await?

Asked

Viewed 1,361 times

17

I saw that it is now possible to use Keywords async and await in javascript, but how it really works?

2 answers

16


Asynchronous Functions

First of all we need to say that these Keywords are part of ES2017 (Ecmascript Latest Draft (ECMA-262)).

Let’s go in pieces, first on the async. In declaring a async Function, you will be, as its 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 don’t already know, what they are Promises, a feature already known to the Javascript community a few years ago. The following is a brief explanation:


Promises

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

When receiving the Promise object, it may be in the pending, realized, rejected, or established states. That is you may have an object in hand that will soon have a value, but currently you do not, you have only the promise that at some point this value will be filled, or not, if something goes wrong along the way.

Now that we know about the Precedents objects, and that they already function asynchronously, what is the purpose of the functions async then? Let’s look at an example of a:

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 as to the explanation, this piece of code is basically a function that returns a precedent 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 method then execute processarDadosNoWorker(v).

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


Using Asynchronous Functions

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

For this whole story to be 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 instruction await in the instruction of Return, because the value returned from an async function is implicitly passed by a Promise..


Completion

To conclude async is used to perform functions asynchronously, i.e., functions that take time and would 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 stand still waiting for the server’s answer, an asynchronous function would be ideal for this.

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

11

What is async/await?

The async/await is the third and most modern way to work with asynchronous functions.

This new type of functionality, released in version ES2017 (ES7), brings to Javascript the first truly asynchronous function and is another tool for work asynchronous processes as the Promises and callbacks.

Interestingly the async/await syntax is the closest to sequential (non-synchronous) code, since it allows writing the code flow in a sequential manner, and the function async is to "pause" the execution until you have an answer to give.

How to use?

Simple, two rules:

  • using async before the word function in statement of their function await in its body/content/interior.

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

One aspect to bear in mind is that async function always returns a Promise, and therefore we use the .then to receive a reply from a async function.

Example with 2 variants:

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

// 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');
});

Browser other questions tagged

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