Multiple chained deferred functions using q in AngularJS stop returning data -
i trying chain multiple deferred function calls such next call gets results of previous deferred.resolve. when chain more 2 of these calls, data stops being returned.
here basic code inside angular controller:
$scope.runasync = function() { var asyncfn1 = function(data){ var deferred = $q.defer(); $timeout(function(){ console.log("async fn1 " + data); $scope.outputlines.push("async fn1 " + data); deferred.resolve("async fn1 " + data); },1000); return deferred.promise; } var asyncfn2 = function(data){ var deferred = $q.defer(); $timeout(function(){ console.log("async fn2 " + data); $scope.outputlines.push("async fn2 " + data); deferred.resolve("async fn2 " + data); },1000); return deferred.promise; } asyncfn1(1) .then(function(data){asyncfn2(data)}) .then(function(data){asyncfn2(data)}) .then(function(data){asyncfn2(data)}); }
when run following output:
async fn1 1 async fn2 async fn1 1 async fn2 undefined async fn2 undefined
how can chain them third call gets result second call , fourth gets result third?
i have created jsfiddle: http://jsfiddle.net/rhdyl/
excerpt taken official doc on $q:
then(successcallback, errorcallback) – regardless of when promise or resolved or rejected calls 1 of success or error callbacks asynchronously result available. callbacks called single argument result or rejection reason.
this method returns new promise resolved or rejected via return value of successcallback or errorcallback.
and return value of successcallack or errorcallback, according domenic's slides:
if return value promise promise adopts returned promise's state otherwise success callback called return value
based on definition, code missing return
keyword. should following:
asyncfn1(1) .then(function(data){return asyncfn2(data)}) .then(function(data){return asyncfn2(data)}) .then(function(data){return asyncfn2(data)});
Comments
Post a Comment