JavaScript · ES2017

ES8 Interactive Hub — ECMAScript 2017

A game-changer for async code: async/await officially ends the callback era. Plus Object.entries/values, String.padStart/padEnd.

Experience
0 XP
Course completion0%

async / await

Core topic

Hard12 min

💡 Concept summary

Syntactic sugar wrapping Promises, letting you write asynchronous code that looks and reads like synchronous code.

🤔 Why do you need this feature?

Promises solved callback hell but are still verbose with chains of .then(). async/await lets you write async code in a sequential style that is easy to debug and easy to try/catch just like synchronous code.

Before (old style)Verbose / clunky
// Traditional Promise chain (ES6)
function fetchUser(id) {
    return fetch('/api/users/' + id)
        .then(function(res) {
            if (!res.ok) throw new Error('Not found');
            return res.json();
        })
        .then(function(user) {
            return fetch('/api/posts?user=' + user.id);
        })
        .then(function(res) { return res.json(); })
        .catch(function(err) { console.error(err); });
}
ES8 (Modern)Optimal & recommended
// async / await ES8 — reads naturally like synchronous code
async function fetchUser(id) {
    try {
        const res = await fetch(`/api/users/${id}`);
        if (!res.ok) throw new Error('Not found');
        const user = await res.json();
        const postsRes = await fetch(`/api/posts?user=${user.id}`);
        return await postsRes.json();
    } catch (err) {
        console.error(err);
    }
}
Got it down? Try running real code or take the quiz!

ES8 Quick Reference

Quick syntax overview + copy snippets

async / await

Syntactic sugar wrapping Promises, letting you write asynchronous code that looks and reads like synchronous code.

async function fetchUser(id) {
    try {
        const res = await fetch(`/api/users/${id}`);
...
Object.entries() & Object.values()

Two static methods that extract an array of [key, value] pairs or an array of values from an object.

const user = { name: "Lan", age: 25, city: "HCM" };
Object.entries(user).forEach(([key, value]) => {
    console.log(`${key}: ${value}`);
...
String padStart / padEnd

Two methods that add characters at the start or end of a string until it reaches the desired length.

console.log('5'.padStart(3, '0'));   // '005'
console.log('42'.padStart(6, '*'));  // '****42'
console.log('42'.padEnd(6, '.'));    // '42....'
...