简体   繁体   中英

How to make $http.get return response instead of promise object?

var final;
final = $http.get('http://localhost:9000/therapist_data',config)
             .success(function(response) {
            console.log("I got the data I requested");
            var resdata = response;
            console.log(resdata);
            return resdata;
        });

console.log(final);

I am trying to return response data and store it into final variable instead I am getting the promise object.
How do I return actual data?

I'll try to develop Cyril answer based on your code :

var final;
final = $http.get('http://localhost:9000/therapist_data',config)
         .success(function(response) {
        console.log("I got the data I requested");
        var resdata = response;
        console.log(resdata);
        return resdata;
    });

console.log(final);

Here is the order of execution :

  1. var final
  2. $http.get('http://localhost:9000/therapist_data',config) .success(); : this will trigger the request and register the function in success as a callback when server will have respond to your request
  3. console.log(final); -> so still undefined. It does NOT WAIT for the response.
  4. some times later ... your function in the success is called.

This is the very basis of callbacks and asynchonous processing, you don't know when it will be executed, or at least, it will often be executed after all the other code. In angularJS there is no way of doing a synchronous request. You must move you code in the success function.

As long as you are making a network call, your data will return back asynchronously, it is the nature of it, you can't fight it.

var wrongFinal; // <-- nope, final will never get into that scope
$http.get('http://localhost:9000/therapist_data',config)
     .success(function(response) {
     console.log("I got the data I requested");
     var goodFinal = reponse; // <-- yes, here, the data lived
     // do something with the data here
});

console.log(wrongFinal); // nop, wrong scope, no sense, data doesn't live here

Soooooo, the answer is a question:

What do you want to do with your data?

It depends on the destination. Are you going to make anoher network call? Do you want to update the view? Do you want to call a 3rd party library?

You need to understand and to embrace the nature of asynchronous in JavaScript.

$http.get will always return a promise.
If you'd like to get the promise value you should do it inside the success callback, like this:

var final;
$http.get('someUrl').success(function(response) {
final = response;
}); 

No need for resData, will only cause a promise chain, something you don't require in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM