Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lint warning for invoking an async function without `.then()` or `await` without TypeScript

Tags:

In TypeScript, it is possible to check and warn the developer if they are calling an async function synchronously.

For those that want less overhead and using node.js v9.0+, is it possible to have any linter give us a warning if we have something like this?

async function foo() {
  return;
}

var result = foo(); // warning right here because there is no await

The reason being is that it is not apparently if a function is returning a promise/is await unless we explicitly name it fooAsync, look into the implementation, or assume everything is async. Or maybe devs messed up and forgot to write await.

Just want a warning to catch errors at dev time and not runtime.

like image 864
PGT Avatar asked Apr 26 '18 16:04

PGT


People also ask

What happens if async function is called without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Can I use async function without await?

In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. Code after each await expression can be thought of as existing in a .then callback.

How do you wait for async to finish without await?

To clean this up, we can use . map instead of a for loop and create an array of Promises, then use Promise. all to wait for them to complete. async function loadContent() { const posts = await getBlogPosts(); // instead of awaiting this call, create an array of Promises const promises = posts.

What happens if you don't use await JavaScript?

Without using await, a promise is returned, which you can use as per need.


1 Answers

No, that is not possible. As you say, it requires type inference or at least annotations to decide whether a function will return a promise. That's what a typechecker like the TypeScript compiler does, not a linter.

like image 144
Bergi Avatar answered Oct 12 '22 23:10

Bergi