在 VSCode 的 JavaScript 方法中检测缺失的 await

Detect missing await in JavaScript methods in VSCode

我正在搜索一些 eslint 选项,或者在调用 class 中的异步方法之前检测缺少 'await' 关键字的其他方法。考虑以下代码:

const externalService = require('./external.service');

class TestClass {

constructor() { }

async method1() {
    if (!await externalService.someMethod()) {
        await this.method2();
    }
}

async method2() {
    await externalService.someOtherMethod();
}

module.exports = TestClass;

如果我将 method1 转换为:

,则不会有警告
async method1() {
    if (!await externalService.someMethod()) {
        this.method2();
    }
}

我尝试在“.eslintrc”文件上做:

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

但没有运气。任何人都知道是否有可能? 非常感谢!

require-await 说“不要创建函数 async,除非你在其中使用 await”。

这是因为async有两个作用:

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

前者很少有用,这意味着如果您没有在函数内部使用 await,您需要质疑为什么将其标记为 async


no-return-await 阻止你做:

return await something

因为 await 从 promise 中解包一个值,但是 return 从 async 函数中获取一个值将它包装在一个 promise 中。

由于只是return承诺会导致该承诺被采纳,因此将returnawait结合起来只是膨胀。


所以这些都不符合您的要求。

这让我们了解了您的实际需求。

ESLint 中不存在这样的功能(据我所知),我认为拥有一个也没有用。

有很多用例,您不想等待 return 由 async 函数编辑的内容。

例如

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

以上是一个常见的用例,您希望 运行 并行执行一堆异步函数,然后等待它们全部解析。

再比如no-return-await就是为了检测!

像这样的情况很常见,大多数人不希望他们的工具链要求他们这样做。

typescript-eslint has a rule for this: no-floating-promises

This rule forbids usage of Promise-like values in statements without handling their errors appropriately ... Valid ways of handling a Promise-valued statement include awaiting, returning, and either calling .then() with two arguments or .catch() with one argument.

正如您可能从名称中看出的那样,typescript-eslint 旨在为 eslint 添加 TypeScript 支持,但您也可以将其与 JavaScript 一起使用。我想由您来决定这条规则是否过大,但步骤如下:

  1. 生成 tsconfig.json 文件

    npx tsc --init
    
  2. 安装依赖项

    npm install --save-dev eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser
    
  3. 修改您的 .eslintrc 文件

    根据我的测试,您似乎至少需要这些条目:

    {
      "parser": "@typescript-eslint/parser",
      "parserOptions": { "project": "./tsconfig.json" },
      "plugins": ["@typescript-eslint"],
      "rules": {
        "@typescript-eslint/no-floating-promises": ["warn"]
      }
    }
    

    (我将它设置为 warn,因为 ,有一些有效的时间你想调用一个 returns Promise 的函数而不使用 await。但是如果您愿意,可以将其设置为 error。)

有关设置 typescript-eslint 的文档可在此处获取更多信息:https://typescript-eslint.io/docs/linting/linting

下次 运行 eslint 时,您应该会看到应用的规则:

$ npm run lint
...
./services/jobService.js
  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: