Loading image with Promise (JS)

by Chris

HTML

<div id="image-holder"></div>
<script>
  function loadImage(url) {
    return new Promise((resolve, reject) => {
      let img = new Image();
      img.addEventListener('load', e => resolve(img));
      img.addEventListener('error', () => {
        reject(new Error(`Failed to load image's URL: ${url}`));
      });
      img.src = url;
    });
  }

  // load the image, and append it to the element id="image-holder"
  loadImage('http://thecatapi.com/api/images/get?format=src&type=jpg&size=small')
    .then(img => document.getElementById('image-holder').appendChild(img))
    .catch(error => console.error(error));

</script>