首页 > web前端 > js教程 > 什么时候使用'.then(success, failed)”作为 Promise 的反模式?

什么时候使用'.then(success, failed)”作为 Promise 的反模式?

Barbara Streisand
发布: 2024-12-25 22:15:13
原创
549 人浏览过

When is Using `.then(success, fail)` an Antipattern for Promises?

.then(success, failure) 何时被视为 Promise 的反模式?

Bluebird 的 Promise 常见问题解答建议使用 .then(success, failure) 是一种反模式。这是因为 .then() 调用返回一个承诺,如果回调抛出错误,该承诺将被拒绝。因此,当 success logger 回调失败时,错误将传递给以下 .catch() 回调,但不会传递给与 success 回调一起提供的失败回调。

控制流图:

[带有两个参数的 then 的控制流程图图像 then catch链]

同步等效:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

// some_promise_call().then(logger.log, logger.log)

then: {

    try {

        var results = some_call();

    } catch(e) {

        logger.log(e);

        break then;

    } // else

        logger.log(results);

}

 

// some_promise_call().then(logger.log).catch(logger.log)

try {

    var results = some_call();

    logger.log(results);

} catch(e) {

    logger.log(e);

}

登录后复制

模式原理:

通常,错误会在每一步中被捕获处理和错误处理是集中的,因此所有错误都由单个最终处理程序处理。然而,反模式中提到的模式在以下情况下很有用:

  • 需要在给定步骤中专门处理错误。
  • 如果没有错误发生,后续操作将显着不同。

此模式可以在控件中引入分支 flow.

推荐模式:

不要重复回调,请考虑使用 .catch() 和 .done():

1

2

3

4

5

6

7

some_promise_call()

   .catch(function(e) {

       return e; // it's OK, we'll just log it

   })

   .done(function(res) {

       logger.log(res);

   });

登录后复制

您也可以考虑使用 .finally().

以上是什么时候使用'.then(success, failed)”作为 Promise 的反模式?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板