【问题标题】:Ajax .then() chains/promises with an If-Else flowAjax .then() 使用 If-Else 流链接/承诺
【发布时间】: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()

标签: jquery ajax promise


【解决方案1】:

代码变成意大利面条

没有办法解决这个问题。条件分支需要嵌套。

我不确定我是否在正确的时间或针对每个依赖项捕获失败。

我也不确定,因为不清楚您是将.fail() 调用链接到step1() 启动的链上还是step2() 启动的链上。只有在前一种情况下,所有错误都会被捕获(来自链中的所有 Promise,包括从回调返回的错误,如条件链的 Promise)。

也就是说,请确保使用现代版本的 jQuery,并更好地使用标准的 .catch 方法而不是 .fail(不链接)。

function addEventItem(params) {
    step1().then(function(data) {
        var statusOK = checkStatus();
        if (statusOK) {
            return step2().then(function(data) {
                return step3();
            }).then(function(data) {
                return step4();
            });
        }
    }).catch(function(jqXHR, textStatus, errorThrown) { 
        alert('A system error occurred and your action could not be completed. Please try again.');
    });
}

【讨论】:

  • 看起来像 catch(function() ..) 没有 3 个失败参数。所以如果我们不需要单独的失败,用 catch() 替换所有的 fail() 调用总是一个好主意?
  • 区别在于.catch为错误处理回调的结果返回一个新的promise,而fail只是附加回调并返回原来的promise。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
  • 2021-10-17
  • 2017-04-06
  • 2023-03-18
  • 1970-01-01
  • 2016-06-16
相关资源
最近更新 更多