【问题标题】:What JS error help prevent with typescript error when it is Functions that return promises must be async @typescript-eslint/promise-function-async当返回承诺的函数必须是异步时,JS 错误有助于防止 typescript 错误 @typescript-eslint/promise-function-async
【发布时间】:2020-11-30 11:49:19
【问题描述】:

我觉得这没有必要。难道这个错误规则是为了防止promise that return,no error?这个错误有什么帮助?

我看了官方文档https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/promise-function-async.md

但我不明白这里的真正含义:

非异步 Promise - 返回函数在技术上都可以。处理这些函数结果的代码通常需要同时处理这两种情况,这会变得很复杂

both 指的是解决还是拒绝或其他?

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    解释the rule's documentation 中的描述:如果一个函数既可以抛出同步错误又可以返回被拒绝的承诺,那么编写代码来处理它是很困难的。这条规则确保一个函数要么做一个,要么做另一个,从不两者兼而有之。

    例如,如果一个函数可能同时出现同步错误和异步错误,那么处理它们需要这样:

    function example (obj) {
      // this might throw synchronously
      const result = JSON.stringify(obj);
      // This might reject (asynchronously)
      return new Promise((resolve, reject) => {
       if (Math.random() > 0.5) {
         resolve(result);
       } else {
         reject('too bad');
       }
      });
    }
    
    try {
      example({ foo: 'bar' })
        .catch(err => {
          // Have to split my error handling to two places, not one    
        });
    } catch (err) {
     // Have to split my error handling to two places, not one
    }
    

    而不仅仅是一个捕获

    example({ foo: 'bar' })
      .catch(err => {
        // All error handling in one place
      });
    

    与所有 lint 规则一样,如果您觉得它没有用,请随意禁用它。

    【讨论】:

    • 所以 IOW,它只允许返回一个被拒绝的承诺,并且没有抛出错误。正确的?你能举例说明这条规则是如何防止代码复杂性的吗?
    • 是的。这是为了确保如果快乐的路径将返回一个已解决的承诺,那么悲伤的路径将返回一个被拒绝的承诺(而不是抛出)
    猜你喜欢
    • 2016-06-22
    • 2022-12-11
    • 2020-04-30
    • 2019-04-25
    • 2020-12-26
    • 2018-12-02
    • 2019-02-02
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多