Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

246
Vistas
FileReader and for loop, how to wait for the last iteration to be completed?

I am kinda new to JavaScript and async programming, I've been battling with this problem for a couple days and I can't figure out what I am doing wrong.

I have a file input element in my HTML, but I can add more input elements when pressing a button.

I want the user to upload images, read them with FileReader() and send them to the backend, here is my javascript code.

function uploadLayers() {
    var listaImagenes = []
    for (let i = 1; i <= currentLayer; i++) {
        for (let j = 0; j < document.getElementById("archivos-" + i).files.length; j++) {
            let archivoActual = document.getElementById("archivos-" + i).files[j]
            var promesa = new Promise(function (resolve, reject) {
                let reader = new FileReader()
                reader.readAsDataURL(archivoActual)
                reader.onload = function () {
                    listaImagenes.push(reader.result) 
                    resolve(listaImagenes)                                                         
                }                          
            })
        }
    }

    promesa.then((resultado) => {
        console.log(resultado.length)
    })
}

The first for loop aims for the input element, the second for loop iterates over the files of each input element.

Everything works "fine", but when I console.log() the result of the promise (the length of the variable "listaImagenes") I get different results, for example if I try to upload 22 items the result will log 20 or 21, but if I log "listaImagenes" only, not the length but the actual list, I can see 22 items there.

I am almost 100% sure that I am not understanding the way async works, any help is appreciated.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda