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

OrA*_*yag 8 javascript node.js eslint visual-studio-code eslintrc

我正在寻找一些 eslint 选项,或者其他一些方法来在调用类内的异步方法之前检测是否缺少“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;
Run Code Online (Sandbox Code Playgroud)

如果我将 method1 转换为:

async method1() {
    if (!await externalService.someMethod()) {
        this.method2();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

"require-await": 1,
"no-return-await": 1,
Run Code Online (Sandbox Code Playgroud)

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

bma*_*pin 10

typescript-eslint有一个规则:no-floating-promises

这一规则禁止在语句中使用类似 Promise 的值,而不适当处理它们的错误...处理 Promise 值语句的有效方法包括awaiting、返回以及使用.then()两个参数或.catch()一个参数进行调用。

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

  1. 生成tsconfig.json文件

    npx tsc --init
    
    Run Code Online (Sandbox Code Playgroud)
  2. 安装依赖项

    npm install --save-dev eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser
    
    Run Code Online (Sandbox Code Playgroud)
  3. 修改你的.eslintrc文件

    根据我的测试,您至少需要以下条目:

    npx tsc --init
    
    Run Code Online (Sandbox Code Playgroud)

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

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

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

npm install --save-dev eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser
Run Code Online (Sandbox Code Playgroud)

由于您特别提到了 VS Code,因此它也与ESLint 插件集成得很好:

vscode 显示 no-floating-promises 规则