【发布时间】:2014-03-19 01:41:23
【问题描述】:
我想使用$q 运行事件,但我确实(出于与问题无关的原因)关心它们发生的顺序。我如何使用promise.then() 来按顺序运行事件没有以重度嵌套函数告终?
简化示例
var myGenericFunc = function(arg1,arg2){
var defer = $q.defer();
doSomeQueryNotActualSyntax(arg1,arg2, someSuccessCallback(){
defer.resolve('result');
}
return defer.promise;
}
// then somewhere else...
var result1,result2,result3,result4;
myGenericFunc('foo','bar').then(function(res){
result1 = res;
myGenericFunc('baz','qux').then(function(res){
result2 = res;
myGenericFunc('quux','corge').then(function(res){
result3 = res;
myGenericFunc('grault','garply').then(function(res){
result4 = res;
});
});
});
});
我知道我可以命名这些嵌套函数并使用f1().then(f2).then(f3).then(f4),但有更好的方法吗?
【问题讨论】:
-
f1.then(f2).then(f3).then(f4)就是这样。每个函数都应该返回一个 promise。 -
谢谢,效果很好。
-
(接受的答案其实是一回事)