javascript - 如何在axios get之外设置变量

标签 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
  }

如何访问“then”中的 name 变量并返回它?

最佳答案

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

关于javascript - 如何在axios get之外设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44231366/

相关文章:

javascript - ionic 框架 : Can't redirect to another page from my controller?

javascript - 尝试了解如何将 Jade 与 Node.js 结合使用

authentication - Nuxt Auth - 未设置用户数据

javascript - 无法理解 `setTimeout()` 中的最小超时值

javascript - 响应式多级菜单

javascript - 使用来自 firebase 的数据填充 React-Table

javascript - 根据 Javascript 中的条件设置 header

reactjs - 检查axios库中是否返回404错误

asp.net - 多个网页的单个 javascript 函数

node.js - Express session 在来自 React 前端的 api 调用之间不持久