javascript - $q defer in angular -


i simplified code solve specific problem.

i have 2 functions @ $scope: singlerequest() , multireqest(). multireqest() must call testserver() several time , call singlerequest().

problem in example: singlerequest() called before multireqest() started, @ same time console.log('all requests multirequest loaded') called in turn. why happening? 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 multirequest loaded');         //do smth 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 data     }); }; // // $scope.multirequest = function (_callback) {     console.log('start multirequest function');     var promises = [];     (var = 1; <= 3; i++) {         promises.push(testserver(i));     }     $q.all(promises).then(function () {         console.log('all requests multirequest loaded');         _callback;     }); }; // $scope.multirequest($scope.singlerequest()); } 

console log:

  • start singlerequest function
  • start multirequest function
  • testserver: 1
  • testserver: 2
  • testserver: 3
  • single request loaded. xhr finished loading: "http://...
  • 1 "request multirequest loaded". xhr finished loading: "http://...
  • 2 "request multirequest loaded". xhr finished loading: "http://...
  • 3 "request multirequest loaded". xhr finished loading: "http://...
  • all requests multirequest loaded

you're not passing callback, calling function here:

$scope.multirequest($scope.singlerequest()); // passing return value 

so should change to:

$scope.multirequest($scope.singlerequest); // passing function 

then change _callback; _callback();, call function.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -