【发布时间】:2018-01-06 01:01:18
【问题描述】:
我在将 .then() 流与 If-Else 流同步时遇到了一些问题。代码变成了意大利面条,我不确定我是否在正确的时间或针对每个依赖项捕获fail。
我需要序列
1. Execute `step1`
2. Check `status` var; if OK
2a. Proceed to `step2`
2b. Proceed to `step3` with dependency on step2
2c. Proceed to `step4` with dependency on step3
Error Check: For any item in the chain, handle it with the error msg in `fail`.
代码:
function addEventItem(params) {
return step1()
.then(function(data) {
var statusOK = checkStatus();
if (statusOK) {
return step2()
.then(function(data) {
return step3();
})
.then(function(data) {
return step4();
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert('A system error occurred and your action could not be completed. Please try again.');
});
我能确定吗
- Step2 将在正确的情况下被链接,仅当 statusOK = true 而不是否则?
- Fail 会捕获函数中任何位置的所有故障吗?
【问题讨论】:
-
您的括号/大括号不平衡,因此您的问题无法回答。但是,是的;你在正确的轨道上。
-
我的意思是...是吗?
-
你可以将你的 .then 简化为 .then(step3).then(step4) 假设它们都返回一个承诺。 (如果他们没有,那么您的代码无论如何都不会按预期运行)
-
@KevinB - 更重要的是 - 你可以只使用
return step2()并将.then链接到原始的step1()