[Vuejs]-Vue JS – How to get function result in methods()

1👍

getStationList is an async function, so you’ll need to await it’s result (or use then). For example:

async mounted() {
  this.markers = await DashboardService.getStationList();
},

Also see this question for more details.

Next, you are missing a return in the implementation of getStationList.

const DashboardService = {
  getStationList() {
    const url = '/api/stations/list';
    ApiService.get(url).then(response => {
      return response.data;
    });
  },
};

or perhaps:

const DashboardService = {
  async getStationList() {
    const url = '/api/stations/list';

    try {
      const response = await ApiService.get(url);
      return response.data;
    } catch (error) {
      console.error(error);
      return [];
    }
  },
};

0👍

The result is undefined because getStationList is not returning anything.

You can consider turning your api call into an async function that returns the result.

const DashboardService = {
    async getStationList() {
        let url = '/api/stations/list';
        return ApiService.get(url);
    }
}

export default DashboardService

And in your component

methods: {
    async getMarkers() {
        let result = await DashboardService.getStationList();
        console.log(result);

   }
},

If you don’t want to use the async await syntax. You can return a the promise from your service and utilize the result on your component, as so:

methods: {
    getMarkers() {
        DashboardService.getStationList().then(result => {
            console.log(result);
        });
   }
},

Leave a comment