JSFiddle - React, Tailwind, and code Playground

by brigand

JavaScript

function asLoaded(img) {
  if (img.complete) {
    return Promise.resolve(img)
  } else {
    return new Promise((resolve, reject) => {
      img.addEventListener('load', () => {
        console.log('Loaded', img.src);
      })
      img.addEventListener('load', () => resolve(img))
      img.addEventListener('error', () => reject(new Error('Failed to load image ' + img.src)))
    })
  }
}

const urls = [
  'https://via.placeholder.com/150',
  'https://via.placeholder.com/300',
  'https://via.placeholder.com/450',
]

const images = urls.map(url => Object.assign(new Image(), {
  src: url
}));

async function main() {
  console.log('Loading all')
  const loaded = await Promise.all(images.map(asLoaded))
  console.log('All loaded')
  console.log('Loading all again')
  const loaded2 = await Promise.all(images.map(asLoaded))
  console.log('All loaded again')
}

main()