How to synchronously call multiple functions angularjs -
for example, have 4 functions:
var f1 = function() {...}; var f2 = function() {...}; var f3 = function() {...}; var f4 = function() {...}; var fmain = function() {...};
the main function loop:
var fmain = function () { angular.foreach(question_list, function (question, key) { f3(); //i want execute f4() after f3() returned! f4(); }); };
in f3()
, f2()
called!
var f2() = function(){ //there's timeout function check if dynamic value equals expected value //if so, return true; otherwise, keep calling f2() until dynamic value equals expected value }
in f2()
, f1()
called!
var f1() = function(){ //there's timeout function check if dynamic value equals expected value //if so, return true; otherwise, keep calling f1() until dynamic value equals expected value }
so, f3
depends on f2
, f2
depends on f1
.
i want have them return synchronously (need code not proceed next line if previous line not returned yet). how can implement this?
thanks in advance!
you can use $q
service:
var f1() = function(){ var defer = $q.defer(); $timeout(function(){ defer.resolve(f1result); }); return defer.promise; } var f2() = function(){ var defer = $q.defer(); f1().then(function(f1result){ defer.resolve(f2result); }); return defer.promise; }
f3 function work f1 , f2 (defer,promise , resolve).
var fmain = function () { angular.foreach(question_list, function (question, key) { f3().then(function(f3result){ f4(); }); }); };
Comments
Post a Comment