Diskdrive
Diskdrive

Reputation: 18825

How to get Javascript to wait for an asynchronous call before proceeding?

I have a factory which goes to the server to grab some reference data.

The problem through is that the http get call below is asynchronous, so as soon as it's called, it goes to the next line. So with the code below, it'll return data as null because by the time the http call finishes, and my callback starts, to copy to the data variable, it has already exitted the method.

How can I get it to wait till the callback function has run before proceeding to the next line?

I'm using Angular here by the way.

app.factory('referenceDataFactory', ['$http', function ($http) {
    var factory = [];

    factory.getSports = function () {

        var data;
        $http.get('/Home/GetSports').success(
            function (obj) {
                data = obj;
            });

        return data;    


        // return [{ id: 1, name: 'Volleyball' }, { id: 2, name: 'Football' }, { id: 3, name: 'Tennis' }, { id: 4, name: 'Badminton' }];
    }


    return factory;

}]);

Upvotes: 0

Views: 1654

Answers (1)

Riri
Riri

Reputation: 11947

The http API will in AngularJs will return a promise. You should return that whole promise instead and the have you're code inside the "success" callback back in your functions that calls into "getSports".

Here's an example.

var app = angular.module('myApp', []);

app.factory('referenceDataFactory', ['$http', function ($http) {
    var factory = [];
    factory.getSports = function () {
        return $http.get('/echo/js/?delay=6&js="test"')
    }

    return factory;
}]);

function HelloCtrl($scope, referenceDataFactory) {
    referenceDataFactory.getSports().success(function (result) {
        $scope.fromFactory = result;
    });
};

Upvotes: 6

Related Questions