How to use async / await in get request using vue + axios?

0

I have the following code and would like to know how I can implement a try / catch with async / await executing the same function:

import Vue from 'vue'
import axios from 'axios'

new Vue({
  el: '#app',
  data: {
    skills: [],
  },
  mounted() {
    axios
      .get('http://localhost:8080/wp-json/api/v1/skills')
      .then(response => {
        this.skills = response
      }).catch(err => (console.log(err)))
  }
})

Thank you!

    
asked by anonymous 20.05.2018 / 19:08

1 answer

1

If you want to apply async to the code of mounted you can do it as follows:

...
async mounted() {
  try {
    let response = axios.get('http://localhost:8080/wp-json/api/v1/skills')
    this.skills = response
  } catch(e) {
    console.error(e)
  }
}
...
  

Asynchronous functions

     

The async function declaration defines an asynchronous function, which returns an object AsyncFunction .

     

You can also define asynchronous functions using a expression async function .

     

When an asynchronous function is called, it returns a Promise . When the asynchronous function returns a value, the Promise will be resolved with the returned value. When the asynchronous function throws an exception or some value, the Promise will be rejected with the value posted.

     

An asynchronous function may contain an expression await , which pauses the execution of the asynchronous function and waits for the resolution of the Promise passed, and then resumes execution of the asynchronous function and returns the resolved value.

     

Simple Example

function resolverDepoisDe2Segundos(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function adicionar1(x) {
  var a = resolverDepoisDe2Segundos(20);
  var b = resolverDepoisDe2Segundos(30);
  return x + await a + await b;
}

adicionar1(10).then(v => {
  console.log(v);  // exibe 60 depois de 2 segundos.
});

async function adicionar2(x) {
  var a = await resolverDepoisDe2Segundos(20);
  var b = await resolverDepoisDe2Segundos(30);
  return x + a + b;
}

adicionar2(10).then(v => {
  console.log(v);  // exibe 60 depois de 4 segundos.
});
    
24.07.2018 / 14:46