DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. JavaScript
  4. Livecoding: JavaScript Async/Await and Morty's Mindblowers [Video]

Livecoding: JavaScript Async/Await and Morty's Mindblowers [Video]

A web developer creates a fun web application based off Imgur and one of his favorite shows using JS async/await methods.

Swizec Teller user avatar by
Swizec Teller
·
Oct. 06, 17 · Tutorial
Like (3)
Save
Tweet
Share
5.06K Views

Join the DZone community and get the full member experience.

Join For Free

This Sunday, I created an excuse to learn JavaScript async/await: Morty's Mindblowers.

Async/await is meant to be the bestest way to deal with asynchronous code in JavaScript. Even better than promises. And since the web is littered with async/await tutorials, it must be really hard, right?

No... just like Promises, it's nothing but a monad. A nice syntax sugarified monad, but still a monad. You can learn how to use async/await in 10 seconds.

Watch. Read.

If you know Promises, you know async/await. Congratz!

Let's say you want to fetch a list of images from Imgur and narrow it down to videos. With Promises, it looks like this:

class Imgur {
    static URL = 'https://api.imgur.com/3/' ;
    static CLIENT_ID = 'c848e36012571f2' ;

    static gifs(page) {
         return fetch(`${Imgur.URL }gallery/hot/rising/${page}`,
                     {headers: { Authorization: `Client-ID ${Imgur.CLIENT_ID }`} }
        ).then (res => res.json ( ) )
         .then (json => {
             if (json.success ) {
                 return json.data.filter ( ( { type } ) => type === 'video/mp4' ) ;
             } else {
                 throw new Error(json.data.error ) ;
             }
         } )
    }
}

We have a static gifs() method that uses fetch to talk to Imgur and return a Promise. The promise resolves with either a list of Imgur videos, or it rejects with an API error.

Using static lets us call this API without instantiating an object. Imgur.gifs() for instance. Great for when you're using classes to group stuff and don't need objects.

Ok, so this code is pretty readable, right? Fetch data, then parse it, then do things.

With async/await, that same code looks like this:

class Imgur {
    static URL = 'https://api.imgur.com/3/' ;
    static CLIENT_ID = '<your_id>' ;

    static async gifs(page) {
        const res = await fetch(`${Imgur.URL }gallery/hot/rising/${page}`,
                                {headers: { Authorization: `Client-ID ${Imgur.CLIENT_ID }`} } ) ,
              json = await res.json ( ) ;

        if (json.success ) {
            return json.data.filter ( ( { type } ) => type === 'video/mp4' ) ;
        } else {
            throw new Error(json.data.error ) ;
        }
    }
}

I don't know if that's more readable, but I can see the appeal. Your code looks just like any other code. No need to think about async stuff at all.

You have to put async in front of your function name. That wraps it in a Promise. Anything you return is in a Promise monad. Time bubble to use the metaphor from my JavaScript Promises in 2 minutes article.

You peek into that monad using the await keyword. It's like wrapping your code in a .then callback.

That's really all there is to it. Once you say json = await res.json(), anything that uses that json variable gets wrapped in a .then() call.

Any time you use the Imgur.gifs() method, you have to say await and your function must be wrapped in async.

Oh, and you can wrap built-in React lifecycle hooks in async and it works as expected. That part is neat. However, you can't have async getters. That would be cool.

So yeah, we got the JavaScript async/await stuff working in a couple minutes, then we spent some half an hour figuring out how Imgur's API works, and an hour or two trying to use flexbox to make the <video> tag shrink and grow.

And in the end, we got Morty's Mindblowers. It uses cut scenes from an episode of Rick & Morty to show you random gifs from Imgur's front page.

Enjoy!

JavaScript

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Why Every Fintech Company Needs DevOps
  • Easy Smart Contract Debugging With Truffle’s Console.log
  • Java Development Trends 2023
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: