af1223345
af1223345

Reputation: 45

handle axios.get response on vue

I'm following a Vue tutorial and I'm not sure about how to handle the axios.get response without then using await

<script>
// @ is an alias to /src
import axios from 'axios';

export default {
  name: 'home',
  components: {

  },
  data(){
    return {
      fecha: '',
      maximo: new Date().toISOString().substr(0, 10),
      minimo: '1984',
      resultado: null
    }
  },
  methods:{
    async getDolar(dia){
      console.log(`https://mindicador.cl/api/dolar/${dia}`);
      let resultado = await axios.get(`https://mindicador.cl/api/dolar/${dia}`);

      return resultado;
    }
  },
  created(){
      let hoy = new Date().toISOString().substr(0, 10).split('-').reverse().join('-');
      this.resultado = this.getDolar(hoy);
      console.log(this.resultado)//it's a promise
    }
}
</script>

It's possible to get the json response whithout then??

Upvotes: 2

Views: 89

Answers (2)

Milan Karunarathne
Milan Karunarathne

Reputation: 100

Yes, await can do the same. However, async/await is part of ECMAScript 2017 and is not supported in Internet Explorer and older browsers, so you have to use with caution about browser availability of the ECMAScript 2017.

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692121

Wait, as for any promise, you can use await to get its value:

async created() {
  let hoy = new Date().toISOString().substr(0, 10).split('-').reverse().join('-');
  this.resultado = await this.getDolar(hoy);
  console.log(this.resultado.data)
}

Upvotes: 1

Related Questions