2016-11-10 62 views
0

例如,我有四个功能:如何同步调用多个功能angularjs

var f1 = function() {...}; 
var f2 = function() {...}; 
var f3 = function() {...}; 
var f4 = function() {...}; 
var fmain = function() {...}; 

主要功能是一个循环:

var fmain = function() { 
    angular.forEach(question_list, function (question, key) { 

     f3(); //I want to execute f4() after f3() is returned! 

     f4(); 

    }); 

    }; 

f3()f2()被称为!

var f2() = function(){ 
//There's a timeout function to check if the dynamic value equals to the expected value 
//if so, then return true; otherwise, keep calling f2() until the dynamic value equals to the expected value 
} 

f2()f1()被称为!

var f1() = function(){ 
//There's a timeout function to check if the dynamic value equals to the expected value 
//if so, then return true; otherwise, keep calling f1() until the dynamic value equals to the expected value 
} 

所以,f3取决于f2f2取决于f1

我想让它们同步返回(如果上一行没有返回,需要代码不要继续下一行)。我怎样才能实现这个?

在此先感谢!

+0

除非有服务器(api)调用,否则上述所有功能都将同步执行。你能解释一下你有没有异步操作? – Aruna

+0

使用承诺,角度中的$ q模块应该有助于https://docs.angularjs.org/api/ng/service/$q – aliasav

回答

1

您可以使用$q服务:

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功能将工作像f1和f2(推迟,承诺和决心)。

var fmain = function() { 
angular.forEach(question_list, function (question, key) { 
    f3().then(function(f3result){ 
     f4(); 
    }); 
}); 
}; 
0
 return A() 
      .then(function (response) { 
       //this portion of code in then of A() (let's call it function B) will execute only after A() provides a response or is resolved. 
       if (response.isAllowed == true) { 
        otherData = myFactory.getOtherDataFromServiceOne(); 
       } 
       else { 
        otherData = hisFactory.getOtherDataFromServiceTwo(); 
       } 
       return $q.all([ 
        otherData 
       ]).then(function (results) { 
        return { 
         otherData: results[0] 
        }; 
       }); 
      }); 
    } 


    function A() { 
      var isAllowed = myFactory.isAllowed(userId); 
      return $q.all([ 
       isAllowed 
      ]).then(function (results) { 
       return { 
        isAllowed : results[0].data; 
       }; 
      }); 
    }; 

我想在这里指出,$ q.all只被用来表示我们能在这里每一个使用$ q.all的传递尽可能多的功能,否则,你可以简单地使用$承诺。