PenAndPapers PenAndPapers - 1 year ago 50
Javascript Question

Vue methods mixins

I have method getNames inside my mixins file that returns names.

import { default as config } from '../config';
var methods = {
methods: {
getNames() {
return axios.get(API + API.NAMES)
.then( (response) => {
if( response.status == 200 && typeof(response.data) == 'object' ) {
return response.data;
}
});
}
}
};

export default methods;


From my single template file I have imported the mixins/methods file. Now my problem is how can I get the return object data from getNames method. Coz when I tried to

mixins: [
filters,
methods
],
mounted: function() {
var a = this.getNames();
console.log(a);
}


getNames method just returns a Promise

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
__proto__
:
Promise
[[PromiseStatus]]
:
"resolved"
[[PromiseValue]]
:
Object

Answer Source

The axios.get() call is asynchronous and it returns a Promise. It does not return the value from the anonymous function passed to the chained then method.

In order to access that value, you can chain a then method to the returned Promise, like so:

mounted: function() {
  this.getNames().then(a => { console.log(a) });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download