Warn in VS Code when Promise return type is unawaited?

Viewed 781

I'm using Visual Studio Code typescript and am wondering if there is a way for the editor to display some kind of warning whenever there is an async function call (function returns a Promise) but the caller does not await it (so that the programmer does not accidentally assume that a function is synchronous and use it as such).

1 Answers

As long as you are using typescript, the type system should alert you that you can't use a promise wherever you use the resolved value of that promise:

function foo(): Promise<number> {
    return new Promise(resolve => resolve(123))
}

const myNumber: number = foo() // forgot await
// ^ Type 'Promise<number>' is not assignable to type 'number'.

Playground

So, in effect, typescript already does what you want, just not in the way you're thinking.


Also, there are very good reasons that a promise may not be awaited. One maybe that you want a bunch of async operations in parallel, so you collect the promises and pass them Promise.all. Or perhaps you're at the top level which does not allow await, and it's simpler to use then instead.

So instead, just let the type system work as intended and don't worry about it. Doing it wrong will give you type errors like the one above when you start to actual use the awaited values.

Related