angular promise - Angularjs Implemet async task queue -
i have fiddle example, in i'm making 3 consecutive calls service function (emulating $http request interceptor function) returning promise, code below. want second , next calls wait until previous finishes, because second , next ones depend on previous response. im getting
message 1: value returned 6000,
message 2: value returned 600
message 3: value returned 30
but want get
message 1: value returned 10
message 2: value returned 200
message 3: value returned 6000
var myapp = angular.module('myapp', []); myapp.factory('interceptor',['$q','$timeout',function($q,$timeout){ var _fact ={}; var asyntimeout; var _intvalue = 1; var _asynctask = function(time, value){ var deferred = $q.defer(); asyntimeout = $timeout(function(){ _intvalue = _intvalue*value deferred.resolve(_intvalue);},time) return deferred.promise; }; _fact.asynctask = _asynctask; return _fact; }]); myapp.controller('appctrl',['$scope', 'interceptor',function ($scope,interceptor) { interceptor.asynctask(1500, 10).then(function(returnedval){ $scope.message1 = "the value returned " + returnedval;}); interceptor.asynctask(1000, 20).then(function(returnedval){ $scope.message2 = "the value returned " + returnedval;}); interceptor.asynctask(800, 30).then(function(returnedval){ $scope.message3 = "the value returned " + returnedval;}); }])
the template be:
<div ng-controller="appctrl"> <div>message 1: {{message1}}</div> <div>message 2: {{message2}}</div> <div>message 3: {{message3}}</div> </div>
notice, solution should implemented in factory function -nested calls @ controller not solution scenario-, want follow @ interceptor side
myapp.factory('interceptor',['$q','$timeout',function($q,$timeout){ ... var _asynctask = function(time, value){ var deferred = $q.defer(); ***if running previous call wait finishes , then(function(){*** asyntimeout = $timeout(function(){ _intvalue = _intvalue*value deferred.resolve(_intvalue);},time) ***}** return deferred.promise; }; ... return _fact; }]);
give try. stash away promise previous $timeout
, use wait previous operations complete. simplified bit, removing deferred , using $timeout
's promise instead...
myapp.factory('interceptor', ['$q', '$timeout', function ($q, $timeout) { var _fact = {}; var _intvalue = 1; var waitpromise = $q.when(true); var _asynctask = function (time, value) { waitpromise = waitpromise.then(function () { return $timeout(function () { _intvalue = _intvalue * value; return _intvalue; }, time); }); return waitpromise; }; _fact.asynctask = _asynctask; return _fact; }]);
Comments
Post a Comment