await and async replace the promises?


In the following code works async and await, my doubt is that if I use async it is no longer necessary to use promises?

async function getMain() {
  var film = 'hola mundo'
  return film

asked by hubman 08.09.2018 в 04:57

1 answer


Answering your first question, not async and await do not replace   the promises , in fact the two can coexist in the same scenario;   below async and await handle promises to solve the states

On the other hand in your example that you put first should look like this

async function getMain(){
  let message = 'Hola Mundo'
  const response = await (message)

getMain()//aquí mando ejecutar la función

Where, as you can see after the declaration of the function with keyword async , I do:

  • I assign a variable message the value of "hola mundo" I want to print
  • after a constant I equal it with variable message but indicating that it must wait for the resolution of this same with the keyword await
  • later I print the value with the help of console.log()
  • Finally, for the function to work, I only invoke it by its name and a pair of parentheses

    If you need to compare the same exercise but from the perspective of the explicit use of promises , I leave this example also functional

    let message = new Promise(function(resolve, reject){
      let saludo = 'Hola Mundo'; 
    message.then((response) => {
    }).catch((error) => {

    Where you can notice that to this day we have three states of the   promises: resolve , pending and reject

  • Resolve : it is the moment that the code flow worked normal and the contained logic was executed
  • Pending , does not exist as such an error in the code but is waiting to return the result of the promise
  • Rejected : indicates that it was rejected, however unlike a trhow exception, it does not kill the code flow

    With regard to the last question, if it can be the case   multiple await within others; I leave an example that I have with a   Exercise in VueJS and it's functional for me

    getFotos: async function(){
            let data = await(await fetch("")).json()
            this.datos = data
    answered by 08.09.2018 в 05:13