检测VSCode中的JavaScript方法中缺少的等待 [英] Detect missing await in JavaScript methods in VSCode

查看:35
本文介绍了检测VSCode中的JavaScript方法中缺少的等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一些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;

如果我将方法1转换为:

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

我尝试对‘.eslintrc’文件执行以下操作:

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

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

推荐答案

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

此规则禁止在未正确处理语句错误的情况下在语句中使用类似Promise的值...处理承诺值语句的有效方法包括使用await调用、返回,以及使用两个参数调用.then()或使用一个参数调用.catch()

正如您可能从名称中了解到的那样,tyescript-eslint旨在为eslint添加类型脚本支持,但您也可以将其与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因为as Quentin mentioned,所以在不使用await的情况下调用返回承诺的函数是有效的。但如果您愿意,可以将其设置为error。)

有关更多信息,请参阅以下文档: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代码,这也很好地集成了ESLint plugin

这篇关于检测VSCode中的JavaScript方法中缺少的等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆