2017-05-28 22 views
0

我無法使用此函數返回值,因爲它是空的。如何在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變量並返回它?

+0

是的,它不會從我回到 – John

回答

2

您應該返回承諾

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 
    }); 
+0

正確的做法(+1)! @OP瞭解更多信息,請點擊此處https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then – Christos

+0

謝謝@Christos! – Ioan

+0

歡迎你! – Christos