如何在axios get请求外部设置变量

9
我无法使用这个函数返回值,因为它是空的。
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变量并将其返回?


是的,它没有返回任何值。 - John
1个回答

21

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

感谢@Christos! - Ioan
你好,伙计! - Christos
1
我如何访问 Promise 上的内容? - John
1
personObject.name = this.getNameById(id) 返回 null。 - John
我不确定你的响应是什么样子的,但它在 response 对象中。你能给我一个提示它是什么样子的吗? - Ioan
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接