【问题标题】:handle axios.get response on vue在 vue 上处理 axios.get 响应
【发布时间】:2019-12-28 15:33:52
【问题描述】:

我正在学习 Vue 教程,但我不确定如何在没有 then 的情况下使用 await 处理 axios.get 响应

<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>

没有then也可以得到json响应??

【问题讨论】:

  • 标有async 的函数将总是返回一个承诺

标签: vue.js axios


【解决方案1】:

Wait,对于任何 Promise,你都可以使用 await 来获取它的值:

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

【讨论】:

    【解决方案2】:

    是的,await 也可以。但是,async/await 是 ECMAScript 2017 的一部分,在 Internet Explorer 和旧版浏览器中不受支持,因此您必须谨慎使用 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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-05
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 2011-02-10
      • 2021-11-03
      相关资源
      最近更新 更多