Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find missing Await on Async function calls in Node+Typescript+VSCode?

We've deployed bugs in our node app b/c we forgot to prefix async function calls with "await".

Example:

const getUsers = async () => db.query('SELECT * from Users');

const testMissingAwait = async () => {
  const users = getUsers(); // <<< missing await
  console.log(users.length);
};

testMissingAwait();

Is there an easy way to find async function calls missing the await keyword?

Failing that, how much effort would it be to write a Visual Studio Code extension that flags these automatically? (I'm up for tackling if anyone can point me in the right direction).

like image 516
1905home Avatar asked Oct 17 '17 20:10

1905home


People also ask

Does Node have async await?

Async functions are available natively in Node and are denoted by the async keyword in their declaration. They always return a promise, even if you don't explicitly write them to do so. Also, the await keyword is only available inside async functions at the moment – it cannot be used in the global scope.

Where is async await and promise?

Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.

Where does await function go in async?

The keyword await before a function makes the function wait for a promise: let value = await promise; The await keyword can only be used inside an async function.


1 Answers

TypeScript compiler doesn't provide a compiler option for that. However, TSLint 4.4 provides an option to detect floating promises. You can read this blog post for more detailed answer: Detect missing await in typescript

Download TSLint:

npm install -g tslint typescript

Configure TSLint:

{
    "extends": "tslint:recommended",
    "rules": {
        "no-floating-promises": true
    }
}

Run TSLint:

tslint --project tsconfig.json

If there are floating promises in your code, you should see the following error:

ERROR: F:/Samples/index.ts[12, 5]: Promises must be handled appropriately

like image 153
meziantou Avatar answered Oct 11 '22 11:10

meziantou