JavaScript Introduction


Example

A function defined as async is a function that can perform asynchronous actions but still look synchronous. The way it's done is using the await keyword to defer the function while it waits for a Promise to resolve or reject.

Note: Async functions are a Stage 4 ("Finished") proposal on track to be included in the ECMAScript 2017 standard.

For instance, using the promise-based Fetch API:

async function getJSON(url) {
    try {
        const response = await fetch(url);
        return await response.json();
    }
    catch (err) {
        // Rejections in the promise will get thrown here
        console.error(err.message);
    }
}

An async function always returns a Promise itself, so you can use it in other asynchronous functions.

Arrow function style

const getJSON = async url => {
    const response = await fetch(url);
    return await response.json();
}