Superagent keeps sending same image repeatedly

70 Views Asked by At

I am trying to be able to upload multiple files and have them sent to Cloudinary's API. I am looping through each image, attaching it and then uploading it. However, my code is looping through the images and then uploading the first image over again for the amount of files:

let uploadRequest = superagent.post(url)

    for (let i=0; i<files.length; i++){
        uploadRequest.attach('file', files[i])
        console.log('file attached', files[i])

        Object.keys(params).forEach((key) => {
            uploadRequest.field(key, params[key])
        })
        console.log('params attached', files[i])

        uploadRequest.then((res) => {

            console.log('UPLOAD COMPLETE: '+JSON.stringify(res.body))
            const uploaded = res.body
            const imageUrl = res.body.secure_url
            let updatedArr = this.state.images.slice();
            updatedArr.push(imageUrl);
                this.setState({
                    images: updatedArr
                })
            })

        .catch((error) => {
            console.log(error)
            return
        })
    }

}

How can I rewrite it to do what I want? confused why this keeps happening

1

There are 1 best solutions below

0
On BEST ANSWER

You can't have asynchronous code in the middle of loop. The loop does not wait for the request to finish.

Move everything to a separate function and then use the loop to call that function.

var uploadFile = function(file){
    //do stuff
}

for(var i=0; i<files.length; i++){
    uploadFile(files[i]);
}