How to wait till the response comes from the $http request, in angularjs? How to wait till the response comes from the $http request, in angularjs? angularjs angularjs

How to wait till the response comes from the $http request, in angularjs?


You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)

An example implementation would be like:

myApp.factory('myService', function($http) {    var getData = function() {        // Angular $http() and then() both return promises themselves         return $http({method:"GET", url:"/my/url"}).then(function(result){            // What we return here is the data that will be accessible             // to us after the promise resolves            return result.data;        });    };    return { getData: getData };});function myFunction($scope, myService) {    var myDataPromise = myService.getData();    myDataPromise.then(function(result) {         // this is only run after getData() resolves       $scope.data = result;       console.log("data.name"+$scope.data.name);    });}

Edit: Regarding Sujoys comment that What do I need to do so that myFuction() call won't return till .then() function finishes execution.

function myFunction($scope, myService) {     var myDataPromise = myService.getData();     myDataPromise.then(function(result) {          $scope.data = result;          console.log("data.name"+$scope.data.name);     });     console.log("This will get printed before data.name inside then. And I don't want that.");  }

Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.

With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)


for people new to this you can also use a callback for example:

In your service:

.factory('DataHandler',function ($http){   var GetRandomArtists = function(data, callback){     $http.post(URL, data).success(function (response) {         callback(response);      });   } })

In your controller:

    DataHandler.GetRandomArtists(3, function(response){      $scope.data.random_artists = response;   });


FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put

myservice.$loaded().then(function() {$rootScope.myservice = myservice;});

and in the view I just did

ng-if="myservice" ng-init="somevar=myfunct()"

in the first/parent view element/wrapper so the controller can run everything inside

myfunct()

without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.