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 一起使用。我想你可以决定这一规则是否太过分,但步骤如下:
生成tsconfig.json文件
npx tsc --init
Run Code Online (Sandbox Code Playgroud)
安装依赖项
npm install --save-dev eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser
Run Code Online (Sandbox Code Playgroud)
修改你的.eslintrc文件
根据我的测试,您至少需要以下条目:
npx tsc --init
Run Code Online (Sandbox Code Playgroud)
如果您想在某些地方不使用 来调用异步函数await,您可以:
使用规则文档void中提到的运算符,例如
void someAsyncFunction();
Run Code Online (Sandbox Code Playgroud)
或者直接改成error上面的配置warn即可.eslintrc
有关设置 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 插件集成得很好:
| 归档时间: |
|
| 查看次数: |
5429 次 |
| 最近记录: |