例如,我有四个功能:
var f1 = function() {...};
var f2 = function() {...};
var f3 = function() {...};
var f4 = function() {...};
var fmain = function() {...};
主要功能是for循环:
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
取决于f2
,f2
取决于f1
。
我想让它们同步返回(如果还没有返回上一行,则需要代码不要进入下一行)。我该如何实现呢?
提前致谢!
答案 0 :(得分: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();
});
});
};
答案 1 :(得分: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中传递尽可能多的函数,否则你可以简单地使用$ promise。