How to use async / await in get request using Vue+Axios?

Asked

Viewed 10,860 times

2

I have the following code and would like to know how I can implement a Try / catch with async / await running 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!

  • Hello wDrik, what is the need to use try/catch? Promise already does that for you. What part of the code do you want to protect against an error?

  • Bro is that I am using Owl.Carousel to display the data that are returning.. only that the sometimes Carousel carega before the items in full and this Buga the layout.. already put a timeout.. msm so ñ solved.. I thought an async await might help! vlw!

  • You probably fill Carousel with the array data skills right? Try to put a v-if="skills.length" probably already solve this problem, no need for Try catch or timeout. If you want to post the whole code that I try later.

  • Blz, man already understood the logic.. so using a Try, catch with async/await should be for a more specific case ? Vlw!

1 answer

6


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

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

Asynchronous functions

The statement async Function defines an asynchronous function, which returns an object Asyncfunction.

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

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

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 the execution of the asynchronous function and returns the solved 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.
});

Browser other questions tagged

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