2016-11-10 51 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的傳遞儘可能多的功能,否則,你可以簡單地使用$承諾。