I’m searching for some eslint option, or some other way to detect missing the ‘await’ keyword before calling async methods inside a class. Consider the following code:
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;
There will be no warning if I will convert method1 to:
async method1() { if (!await externalService.someMethod()) { this.method2(); } }
I tried to do on the ‘.eslintrc’ file:
"require-await": 1, "no-return-await": 1,
But with no luck. Anyone have an idea if it is even possible? Thanks a lot!
Advertisement
Answer
require-await
says “Don’t make a function async
unless you use await
inside it”.
This is because async
has two effects:
- It forces the function to return a promise
- It lets you use
await
inside it
The former is rarely useful which mean if you aren’t using await
inside the function you need to question why you marked it as async
.
no-return-await
stops you from doing:
return await something
Because await
unwraps a value from a promise, but returning a value from an async
function wraps it in a promise.
Since just returning a promise causes that promise to be adopted, combining return
with await
is just bloat.
So neither of those do what you want.
Which brings us to your actual desire.
Such a feature does not (as far as I know) exist in ESLint, and I don’t think it would be useful to have one.
There are lots of use cases where you don’t want to await something returned by an async
function.
e.g.
const array_of_promises = array_of_values.map( value => do_something_async(value) ); const array_of_resolved_values = await Promise.all(array_of_promises);
The above is a common use-case where you want to run a bunch of async functions in parallel and then wait for them all to resolve.
Another example is the case that no-return-await
is designed to detect!
Cases like these are common enough that most people wouldn’t want their toolchain calling them out for doing it.