I have the following code. performAsyncAction
performs an async action and returns Promise<Response>
. In someFunction
, I was surprised that TypeScript doesn’t warn about not using await on a function that returns a promise.
function performAsyncAction() { return fetch('someservice'); } function someFunction() { const result = performAsyncAction(); // Was expecting typescript to give error here }
I found a relevant linting rule that may help promise-function-async
Advertisement
Answer
It is not an error, it is intended behaviour.
- The Promises existed long before async/await, you have several ways how to handle them
- Awaiting promise is internal logic of function, not requirement
- Typescript knows well that you have Promise and not the value inside that Promise, so it will warn you if you want to use it in a wrong way
- The function you have provided is not
async
, therefore it is not even possible to await there - await/async and Promises are the same thing in Javascript, it does not matter if you
await
Promise or if you.then
Promise, its only syntactic sugar (useful one though) - There is a lot of cases where you dont want to await newly created Promise, i.e. to allow processing of several Promises at once, thus reducing the time of processing request