How to set variable outside axios get [duplicate]

旧城冷巷雨未停 提交于 2019-12-01 20:11:30

问题


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
  }

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


回答1:


You should return the promise instead.

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

and use it:

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


来源:https://stackoverflow.com/questions/44231366/how-to-set-variable-outside-axios-get

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!