Archarious
Archarious

Reputation: 43

$q defer in angular

I simplified the code to solve a specific problem.

I have 2 functions at $scope: singleRequest() and multiReqest(). multiReqest() must call testServer() several time and then call singleRequest().

Problem in this example: singleRequest() called before multiReqest() started, but at the same time console.log('All requests from multiRequest loaded') called in turn. Why is this happening? What am I doing wrong? Thanks.

function TestCtrl($scope, $q, $http) {

//variables declaration etc

var testServer = function (_pos) {
    console.log('testServer:', _pos)
    var deferred = $q.defer();
    $http.get(service.first, parameters).success(function (data, status, headers, config) {
        console.log(_pos, 'request from multiRequest loaded');
        //do smth with data
        deferred.resolve();
    }).error(function (err) {
        deferred.reject(err);
    });
    return deferred.promise;
};
//
//
$scope.singleRequest = function () {
    console.log('Start singleRequest function');
    $http.get(service.second).success(function (data, status, headers, config) {
        console.log('Single request loaded');
        //do smth with data
    });
};
//
//
$scope.multiRequest = function (_callback) {
    console.log('Start multiRequest function');
    var promises = [];
    for (var i = 1; i <= 3; i++) {
        promises.push(testServer(i));
    }
    $q.all(promises).then(function () {
        console.log('All requests from multiRequest loaded');
        _callback;
    });
};
//
$scope.multiRequest($scope.singleRequest());
}

console log:

Upvotes: 0

Views: 326

Answers (1)

Knelis
Knelis

Reputation: 7129

You're not passing a callback, but actually calling the function here:

$scope.multiRequest($scope.singleRequest()); // Passing return value

So you should change that to:

$scope.multiRequest($scope.singleRequest); // Passing function

Then change _callback; to _callback();, to call the function.

Upvotes: 1

Related Questions