如何在axios之外设置变量get [英] How to set variable outside axios get

查看:31
本文介绍了如何在axios之外设置变量get的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能使用这个函数返回一个值,因为它是空的.

I can't return a value using this function because it is empty.

getNameById (id) {

    var name = ''

    axios.get('/names/?ids=' + id)
      .then(response => {
        this.response = response.data
        name = this.response[0].name
      })
      .catch(e => {
        this.errors.push(e)
      })
    // Is empty
    console.log('Name ' + name)
    return name
  }

如何访问then"中的name变量并返回?

How do I access the name variable inside "then" and return it?

推荐答案

你应该返回 promise 代替.

getNameById (id) {
  return axios.get('/names/?ids=' + id)
      .then(response => {
        this.response = response.data
        return this.response[0].name
      })
  }

并使用它:

getNameById(someId)
  .then(data => {
    // here you can access the data
  });

这篇关于如何在axios之外设置变量get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆