- 2 min
TypeScript’s New Top-Level Await
If you want to use
async function before you can use the
In this article, I want to show you that it is possible to finally use top-level
await instead of wrapping it between an
Note: The top-level
await is part of a stage 3 proposal for the ECMAScript spec. It may change in the future.
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.
While this has a lot of benefits in making operations non-blocking, it makes certain code for loading files or external content less readable.
But this will execute the function right after the definition, which feels weird. It’s missing the point of using a function.
It would be better to use await without wrapping it in an async function.
With the release of TypeScript 3.8, we received this feature. Take into account that it’s only supported natively in Chrome.
To use it, we have to create a module. It’s a module when it is exporting something via
If you ask me, this code is much more readable. Because we don’t have to create an async function, it also saves a bit of code.
To use top-level
await in TypeScript, you have to set the target compiler option to
es2017 or higher. The
module option has to be set to
I think it’s awesome that the TypeScript team has built top-level
await into the language.
What do you think? Are you going to use it? Please let me know in the comments.
I’ve gathered a couple of aspiring developers around the world on a Discord server, feel free if you like to join in.
Want to reach me for comments or questions on my blog? Send a DM on Twitter @DevByRayRay