Using ES2017 async / await

suggest change

An image load can be written with async functions. await works with try/catch. getElementById can return null.

Async functions are part of modern JavaScript. When supporting an explicitly defined legacy target, verify its syntax and runtime support as part of the project's compatibility policy.

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 the image and append it to #image-holder, or log the error.
    try {
        const img = await loadImage('http://example.com/image.png');
        document.getElementById('image-holder').appendChild(img);
    }
    catch (error) {
        console.error(error);
    }

})();

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents