NodeJS 在VSCode中检测JavaScript方法中缺少的等待

mwg9r5ms  于 2023-02-03  发布在  Node.js
关注(0)|答案(3)|浏览(216)

我正在寻找一些eslint选项,或者其他一些方法来检测在调用类中的异步方法之前是否缺少'await'关键字。

  1. const externalService = require('./external.service');
  2. class TestClass {
  3. constructor() { }
  4. async method1() {
  5. if (!await externalService.someMethod()) {
  6. await this.method2();
  7. }
  8. }
  9. async method2() {
  10. await externalService.someOtherMethod();
  11. }
  12. module.exports = TestClass;

如果我将method 1转换为以下内容,则不会出现警告:

  1. async method1() {
  2. if (!await externalService.someMethod()) {
  3. this.method2();
  4. }
  5. }

我尝试对.“eslintrc”文件执行以下操作:

  1. "require-await": 1,
  2. "no-return-await": 1,

但是没有运气。有人知道这是否可能吗?非常感谢!

v1l68za4

v1l68za41#

typescript-eslint对此有一条规则:no-floating-promises
此规则禁止在未适当处理错误的情况下在语句中使用类似Promise-like的值...处理Promise-valued语句的有效方法包括await ing、return以及使用两个参数调用.then()或使用一个参数调用.catch()
从名称中您可能已经知道,typescript-eslint旨在为eslint添加TypeScript支持,但您也可以将其用于JavaScript。我想这取决于您是否对这一规则过度使用,但以下是步骤:
1.生成tsconfig.json文件

  1. npx tsc --init

1.安装依赖项

  1. npm install --save-dev eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser

1.修改.eslintrc文件
根据我的测试,看起来您至少需要以下条目:

  1. {
  2. "parser": "@typescript-eslint/parser",
  3. "parserOptions": { "project": "./tsconfig.json" },
  4. "plugins": ["@typescript-eslint"],
  5. "rules": {
  6. "@typescript-eslint/no-floating-promises": ["error"]
  7. }
  8. }

如果您希望在某些地方调用异步函数而不使用await,您可以:

  1. void someAsyncFunction();
  • 或者,只需将上述.eslintrc配置中的error更改为warn

有关设置typescript-eslint的文档,请访问以下位置以获取更多信息:https://typescript-eslint.io/docs/linting/linting
下一次运行eslint时,应该会看到应用的规则:

  1. $ npm run lint
  2. ...
  3. ./services/jobService.js
  4. 11:5 warning Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator @typescript-eslint/no-floating-promises

由于您特别提到了VS Code,因此它还可以与ESLint plugin完美集成:

展开查看全部
w8biq8rn

w8biq8rn2#

require-await表示“除非在函数async中使用了await,否则不要创建函数async”。
这是因为async具有两个效果:

  • 它强制函数返回一个承诺
  • 它允许您在其中使用await

前者很少有用,这意味着如果你没有在函数内部使用await,你需要问为什么你把它标记为async
no-return-await阻止您执行以下操作:

  1. return await something

因为await从promise中打开一个值,但是从async函数返回一个值时却将其 Package 在promise中。
由于 * 仅仅 * 返回一个承诺就会导致该承诺被采纳,因此将returnawait结合起来只是膨胀。
所以这两个都不是你想要的。
这就引出了你真正的愿望。

(据我所知)ESLint中不存在这样的特性,而且我认为拥有这样的特性也没有什么用处。

在许多用例中,您不希望等待async函数返回的内容。
例如:

  1. const array_of_promises = array_of_values.map( value => do_something_async(value) );
  2. const array_of_resolved_values = await Promise.all(array_of_promises);

上面是一个常见的用例,您希望并行运行一组异步函数,然后等待它们全部解析。
另一个例子是no-return-await设计用于检测的情况!
像这样的情况很常见,大多数人都不希望他们的工具链叫他们这样做。

展开查看全部
vxqlmq5t

vxqlmq5t3#

有一个ESLint插件可用于此,您可以将其用作typescript-eslint路径的替代方法:
https://github.com/SebastienGllmt/eslint-plugin-no-floating-promise

相关问题