Skip to content
Advertisement

Why doesn’t TypeScript enforce async/await on promise?

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.

  1. The Promises existed long before async/await, you have several ways how to handle them
  2. Awaiting promise is internal logic of function, not requirement
  3. 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
  4. The function you have provided is not async, therefore it is not even possible to await there
  5. 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)
  6. 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
Advertisement