Better Programming

Advice for programmers.

Follow publication

Member-only story

TypeScript’s New Top-Level Await

RayRay
Better Programming
Published in
3 min readJun 22, 2020
Photo by Joshua Aragon on Unsplash.

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 asyncfunction.

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

RayRay
RayRay

Written by RayRay

I’m a 🇳🇱 Tech Lead (frontend) who writes about AI | JavaScript | TypeScript | Vuejs | Design Systems | NuxtJS | CSS | https://www.youtube.com/@devbyray

Responses (1)

Write a response