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).
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.
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.
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.
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
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