首页 > 解决方案 > 当返回 promise 的函数必须是异步的时,JS 错误有助于防止 typescript 错误 @typescript-eslint/promise-function-async

问题描述

我觉得这没有必要。难道这个错误规则是为了防止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解决还是拒绝或其他什么?

标签: typescripttypescript-typings

解决方案


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

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

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 规则一样,如果您觉得它没有用,请随意禁用它。


推荐阅读