Bojan Gvozderac

JavaScript Async / Await

Lets do a quick one today that can make your JavaScript code much cleaner and much much more readable, namely JavaScript Async / Await.

What is Async / Await?

Async / Await is a way to write asynchronous code as if it were synchronous.
This is a big deal because you’re probably writing tonnes of asynchronous code and a majority of it is probably just fetching some data, this quickly becomes a pain in the ass because every time you do this you need to write 5 goddamn lines of code for a simple assignment operation.

F that noise!

Lets look at an example
1const initAsyncData = async () => {
2 const data1 = await somethingAsync();
3 const data2 = await somethingAsync();
4 const data3 = await somethingAsync();
5 return 'finished';
8function somethingAsync() {
9 return new Promise((resolve, reject) => {
10 resolve({ ok: true });
11 });
The code above waits until the first ‘somethingAsync()’ is done then waits for the second one then waits for the third one and finally wraps things up by returning ‘finished’.
Couple of important things to note:
  • ‘await’ can only be used inside ‘async’ functions
  • ‘async’ functions return a promise implicitly
  • Resolve value of the ‘async’ function is whatever we return from it. In our case we resolve ( return ) ‘finished’

  • When can I use this sweet sweet new tech?!
    How about right now, PLAYA!
    Async / Await is a really popular feature that got a lot of people talking so it should come as no surprise that the support is pretty good!
    caniuse (Link) shows that major browser vendors are serious when it comes to Async / Await.
    node support table (Link) paints a similar picture as caniuse. Newer node versions fully support Async / Await!
    If the above isn’t good enough for you you can always use something like Babel (Link) to make sure your Async / Await code runs everywhere.
    If you use TypeScript ( Angular 2+ developers I’m looking at you ) you’ll be happy to learn that it’s been supported for a while now (Link)

    Slow the hype train down

    Async / Await is awesome. Agreed. But don’t get too sucked in to the hype and try to force Async / Await on every single asynchronous call like I’ve seen some developers try to do.
    I don’t consider Async / Await a replacement for Promise.then but a new tool to use alongside it, always use the tool that makes the most sense, is clean and readable.

    Be smart.

    Share Article on:  or 
    Bojan Gvozderac profile image

    Bojan Gvozderac is an experienced web and mobile developer specializing in JavaScript with almost a decade and a half developing software Bojan has proven that he has the knowledge and the expertise to deliver the goods!
    If you'd like to get in touch and talk about potential projects, one of my articles, ask a question or just say "Hi!" please do by clicking  here.