Member-only story
TypeScript’s New Top-Level Await
We don’t need an async function wrapper anymore
If you want to use async
/await
inside JavaScript, in general, you have to define an async
function before you can use the await
.
In this article, I want to show you that it is possible to finally use top-level await
instead of wrapping it between an async
function.
Note: Since Typescript 3.8 it’s released 👍 and all major browser support top-level await.
How Does async/await Work?
In a previous article, I wrote about the history of doing Ajax calls in the early days with XHR until now with the Fetch API.
Promises are an essential part of async
/await
. Without them, we can’t use them.
Most modern environments in JavaScript (like HTTP requests) are asynchronous, and many modern APIs returns promises.
While this has a lot of benefits in making operations non-blocking, it makes certain code for loading files or external content less readable.
fetch("...")
.then(response => response.json())
.then(data => { console.log(data) });
People are used to using promises in JavaScript with a async
function to use await
.
But this will execute the function right after the definition, which feels weird. It’s missing the point of using a function.
I’ve gathered a couple of aspiring developers around the world on a Discord server, feel free if you like to join in.
Top-Level await
It would be better to use await
without wrapping it in an async
function.