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.
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.
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.
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.
Without using await, a promise is returned, which you can use as per need.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With