检测 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;

如果我将method1转换为:

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

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

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

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

解决方法

async 表示“不要创建函数 await,除非您在其中使用 async”。

这是因为 await 有两个作用:

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

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


return await something 阻止你做:

await

因为 async 从 Promise 中解开一个值,但从 return 函数返回一个值会将它包装在一个 Promise 中。

由于只是返回一个承诺会导致该承诺被采用,因此将 awaitasync 结合只是膨胀。


所以这些都不是你想要的。

这使我们能够满足您的实际需求。

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

在许多用例中,您不想等待 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

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

另一个例子是 for (var i = 0; i < n; i++ ) { for (var j = 0; j < m; j++) { Element.addEventListener('click',(event) => { Array [i][j] = true } } } 旨在检测!

像这样的情况很常见,以至于大多数人不希望他们的工具链因为这样做而招呼他们。