【问题标题】:How to set variable outside axios get [duplicate]如何在axios get之外设置变量[重复]
【发布时间】:2017-05-28 19:47:49
【问题描述】:

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

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 变量并返回它?

【问题讨论】:

  • 是的,它不会返回

标签: javascript axios


【解决方案1】:

您应该返回 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
  });

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
相关资源
最近更新 更多