Doubt about Promises and async await?

2

I'm seeing the promises and async await in JavaScript. The syntax to generate both if I understand it and I can create them. What I do not understand is because we use async await if the promises are already created to generate asynchronous tasks. I do not understand why async await. Can you help me understand why each one exists and why is it necessary to use both?

Thank you.

    
asked by kosode 17.10.2018 в 11:58
source

2 answers

3

The general idea of async/wait is to reduce code and make it less noisy.

Usually with the promises, the method then() is used to wait for the answer:

$http.get(url).then(function(){
   //..
});

This translates to:

var response = await $http.get(url);

Imagine now having to wait for an asynchronous process to run another asynchronous process:

$http.get(url).then(function(response){
    //...
    $http.get(url + response.data.id).then(function(){
       console.log(response2.data.message);
    });
});

And with async / await it would be:

var response = await $http.get(url);
var response2 = await $http.get(url + response.data.id);
console.log(response2.data.message);

asyn / await also helps avoid the callback hell and makes the code less noisy in the sense that since the code follows a line constant execution, makes it easier to maintain it.

Note: As already mentioned, you can only use await within a function marked as async .

    
answered by 17.10.2018 / 14:22
source
2

The keywords async/await are to Promise what class is to the classic prototyping of Javascript: sugar syntax .

It's just a different way to create promises without having to use the Promise class directly:

//declaramos una función asincrona
async function  devuelveParam(param) {
  //el resultado se envolverá dentro de una promesa automáticamente
  return param;
}

// Estilo clásico para gestionar una promesa:
let promesa = devuelveParam('Hola'); 

promesa.then(function (p) {
  console.log(p);
});


//con await (ojo, sólo se puede usar await DENTRO de una función async(rona)
async function escribe(param) {
  let resultado = await devuelveParam(param);
  console.log(resultado);
}

escribe('Adios');
    
answered by 17.10.2018 в 12:24