Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
How to wrap an event listener into Promise to make it synchrounous?

I have an array list of image urls. I want to get an image width and height, to do so, I use:

    const url = 'https://via.placeholder.com/350x150'
    const img = new Image()
    img.addEventListener('load', function () {
      const isWide = img.width > img.height
      const isTall = img.height > img.width
      console.log(url, isWide, isTall, img.width, img.height) // <--- WORKS FINE
      img.src = url
    })

I have a list of images where I want to extract them all in some one Promise.all(arrayOfImageUrls).

How would I make it Promise so it awaits for all of the urls in the image array to complete ?

Here is my code which does not work, it just ignores the "await" and trigger the function before it was even finished:

const array = [
  "https://via.placeholder.com/350x150",
  "https://via.placeholder.com/650x250",
  "https://via.placeholder.com/350x150",
  "https://via.placeholder.com/650x250",
  "https://via.placeholder.com/150x550",
  "https://via.placeholder.com/510x450",
  "https://via.placeholder.com/800x800"
]

function doSomethingAsync(url) {
  return new Promise((resolve) => {
    const img = new Image()
    img.addEventListener('load', function() {
      const isWide = img.width > img.height
      const isTall = img.height > img.width
      img.src = url
      resolve({ url, isWide, isTall })
    })
  })
}

async function doAsync() {
  const promises = []

  array.forEach(url => {
    promises.push(doSomethingAsync(url))
  })

  console.log('before promise all')
  const results = await Promise.all(promises)
  console.log('after promise all', results)
}
doAsync()

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have to put img.src = url before waiting for the images to load, not inside the onload handler. You are currently waiting for images with no src to load.

const array = [
  "https://via.placeholder.com/350x150",
  "https://via.placeholder.com/650x250",
  "https://via.placeholder.com/150x550",
  "https://via.placeholder.com/510x450",
  "https://via.placeholder.com/800x800"
]

function doSomethingAsync(url) {
  return new Promise((resolve) => {
    const img = new Image();

    img.src = url; // <--- Move this line here

    img.addEventListener('load', function() {
      const isWide = img.width > img.height
      const isTall = img.height > img.width
      resolve({ url, isWide, isTall })
    })
  })
}

async function doAsync() {
  const promises = []

  array.forEach(url => {
    promises.push(doSomethingAsync(url))
  })

  console.log('before promise all')
  const results = await Promise.all(promises)
  console.log('after promise all', results)
}
doAsync()

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda