sweetcode
sweetcode

Reputation: 159

How to wait for an http call to get over in js?

I am making a http call to user using $http. I have a success method which gets called on getting the success response from server. My question is how can I wait(i.e not to do what is written after the call till it's done) for http call to get over?

main(){ 
    var val = myFunction();
    console.log("---after receiving response---");
    return val;
}
myFunction(){
    var temp;
    fnResource.get(function(data){
        {
            console.log("---on success---");
            temp = data;
        });     
    return temp;   
}

In this case, my code prints "---after receiving response---" first and then "---on success---", but I intend to have "---on success---" printed first always.

Update: Have updated the snippet to explain my scenario further.

Upvotes: 0

Views: 97

Answers (3)

Lesha Ogonkov
Lesha Ogonkov

Reputation: 1238

Try to use always

myFunction(){
    $http.get("..api/endpoint/").
        success(function(data){
            console.log("---on success---");
        })
        .always(function() {
          console.log("---after receiving response---");
        });
}

Upvotes: 0

Jeff Lambert
Jeff Lambert

Reputation: 24671

Your confusion may be stemming from the fact that AJAX calls are non blocking (as in asynchronous, as in A synchronous J avascript A nd X ML). You can fire off multiple AJAX requests in a row and one will not stop the others from being sent until they are retrieved. Consider this:

$http.get('/route1').success(function() { console.log('route 1 success'); });
$http.get('/route2').success(function() { console.log('route 2 success'); });
$http.get('/route3').success(function() { console.log('route 3 success'); });

The AJAX call out to /route2 and /route3 do not have to wait for the first AJAX call to complete before they are sent. Furthermore, in this case, you cannot guarantee what order in which they will return for a number of different reasons all way out of scope for the purposes of this question. The point is that, running the above code multiple times could result in a log looking like this:

route 1 success
route 2 success
route 3 success

But it is equally likely that it could look like this:

route 2 success
route 1 success
route 3 success

And you have no control over it. You can, however, do something like this to force the HTTP requests to return in a certain order:

$http.get('/route1').success(function() { 
    $http.get('/route2').success(function() { 
        $http.get('/route3').success(function() { 
            console.log('all requests complete');
        });
    });
});

Above the AJAX request to route1 will block the request to route2 until it has returned

Upvotes: 0

Kamil R
Kamil R

Reputation: 447

Just put the code after the $http.get(...) in a separate function and call it from success callback.

Upvotes: 1

Related Questions