dfsq 开始写一个答案,但删除了他的答案,因此在他的祝福下我添加了我的看法:
confirmSteps = function() {
return fetchSomeData()
.then(confirmStep1(data))
.then(confirmStep2(data))
.then(confirmStep3(data));
}
这调用了函数,它与setTimeout(alert("Hi"),5)
你不想调用你想要链接它们的函数。喜欢setTimeout(function(){ alert("Hi"); }, 5)
;
confirmSteps = function() {
return fetchSomeData()
.then(confirmStep1)
.then(confirmStep2)
.then(confirmStep3);
}
不过,这样就过去了data
仅适用于第一个承诺,并将上一个承诺的结果传递给下一个承诺,而不是您想要传递data
对于这三者,您可以通过净一级来做到这一点:
confirmSteps = function() {
return fetchSomeData().then(function(data){
var v1, v2;
return confirmStep1(data).then(function(d){
v1 = d;
return confirmStep2(data);
}).then(function(d){
v2 = d;
return confirmStep3(data);
}).then(function(v3){
return v1 && v2 && v3;
})
});
};
这可行,但有点笨拙,您可以使用短路 - 有点像&&
仅在左侧为 false 时才对其进行评估。此外,我们可以在一个中心位置进行所有错误处理。这会让你的代码看起来像。
confirmStep1 = function(data) {
if (data.condition1) return $q.when(true);
return confirmDialogService.popConfirm('step1');
};
confirmStep2 = function(data) {
if (data.condition2) return $q.when(true);
return confirmDialogService.popConfirm('step2');
};
confirmStep3 = function(data) {
if (data.condition3) return $q.when(true);
return confirmDialogService.popConfirm('step3'):
};
confirmSteps = function() {
var data = fetchSomeData();
return data.then(confirmStep1).then(function(soFar){
if(!soFar) return false;
return data.then(confirmStep2);
}).then(function(soFar){
if(!soFar) return false;
return data.then(confirmStep3);
}).catch(function(){ return false; });
};
作为额外提示:
fetchSomeData = function() {
var deferred = $q.defer();
api.fetchData(param1, param2, param3)
.then(function(data) {
deferred.resolve(data.content);
}, api.errorHandler);
return deferred.promise;
};
可以简单地变成:
fetchSomeData = function() {
return api.fetchData(param1, param2, param3).then(function(data) {
return data.content;
}, api.errorHandler);
};