1

I'm now trying to make get/post api request with axios javascript.But the problem is that my Api get function return the result before it receives data from server.here is my code

function Api(base_url) {
    this.base_url = base_url;
}

Api.prototype = {
    constructor: Api,
    get: function (route) {
        var url = this.base_url + route;

        axios.get(url)
            .then(
                response => {
                    console.log(response.data.data);
                    return response.data.data;
                })
        return "hello";
    },
    post: function (route) {

    }
}

And I call get function like this

api = new Api("http://localhost:8080/");
            var data = api.get("post/get");
            console.log(data);

Instead of waiting for reply from server,my function return "hello" as return data.Can someone help me why and how to solve this please?

Min Htet Oo
  • 188
  • 4
  • 16

2 Answers2

0

Use this code:

Api.prototype = {
    constructor: Api,
    get: function (route) {
        var url = this.base_url + route;

        axios.get(url)
            .then(function (response) {
                console.log(response.data.data);
                return response.data.data;
            })
            .catch(function (error) {
                return "hello";
            }
    },
    post: function (route) {

    }
}
Dmitry Maslennikov
  • 338
  • 2
  • 8
  • 22
0

That's what it is supposed to do, I think. I never used this Api, but with regular ajax requests, the function from which you send the request will return his value immediately independently from the request/response. The best way to do something once the request is completed, is to call what you need in the response callback. AJAX requests are asynchronous, and there is no clean way to call a function wich executes an AJAX requests and make that very same function return your response data - unless you turn the AJAX request into a synchronous operations, but that's very very very bad practice.

Fabio Lolli
  • 859
  • 7
  • 23