如何在axios外设置变量

Joh*_*ohn 5 javascript axios

我无法使用此函数返回值,因为它是空的.

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
  }
Run Code Online (Sandbox Code Playgroud)

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

Ioa*_*oan 11

你应该返回承诺.

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

并使用它:

getNameById(someId)
  .then(data => {
    // here you can access the data
  });
Run Code Online (Sandbox Code Playgroud)