Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

248
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!