0

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.

Alex
  • 81
  • 4

0 Answers0