JavaScript Using ES2017 async/await


Example

The same example above, Image loading, can be written using async functions. This also allows using the common try/catch method for exception handling.

Note: as of April 2017, the current releases of all browsers but Internet Explorer supports async functions.

function loadImage(url) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.addEventListener('load', () => resolve(img));
        img.addEventListener('error', () => {
            reject(new Error(`Failed to load ${url}`));
        });
        img.src = url;
    });
}

(async () => {

    // load /image.png and append to #image-holder, otherwise throw error
    try {
        let img = await loadImage('http://example.com/image.png');
        document.getElementById('image-holder').appendChild(img);
    }
    catch (error) {
        console.error(error);
    }

})();