Using ES2017 async / await
suggest changeAn 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);
}
})();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents