1
var images = [];
let uploader = new Slingshot.Upload("articles"); 

// file input
let files = document.getElementById("someId").files; 

for (let i = 0; i < files.length; i++) { 
    uploader.send(files[i], function (error, downloadUrl) { 
        if (!error) { 
            //save all download urls in an array 
            images[i] = downloadUrl; 
        } 
    }); 
}
console.log(images); 

When I access the images array above after filling it with download urls, it is being empty. Any variable value is lost after the send() block. I would like to store all the download urls in an array, so how do I do this?

  • 1
    Missing closing `)` at `uploader.send()` , closing `}` at `for` loop? Does `uploader.send()` return results asynchronously? – guest271314 Jul 03 '16 at 07:59
  • Yeah I forgot to type it. It sends the file asynchronously and works on one file at each instantiation. As in the code above, I would like to store an array of urls, but this doesn't let me do. – Buyantogtokh Jul 03 '16 at 16:31
  • `console.log(images)` could be called before asynchronous callback completes. You could check if `i` is equal to `files.length` before calling `console.log(images)`; e.g., within callback, `if (i === files.length) {console.log(images)}` – guest271314 Jul 03 '16 at 16:35
  • The reason that console.log() is outside the loop is that I would like to save the whole 'images' array content into a database, after the loop finishes. Thanks for the tips. – Buyantogtokh Jul 03 '16 at 17:44

1 Answers1

0

Slingshot's uploader.send() is an asynchronous process.

Therefore it looks to me that it is just a classic async task misunderstanding.

I.e. console.log(images) is called before uploader.send callbacks are executed.

Furthermore, you will experience scope issue by using your i variable within the callback function. When it executes, i will have a different value. Typically it will already be equal to files.length. Which means all your callbacks will write on the same array item images[files.length].

ghybs
  • 47,565
  • 6
  • 74
  • 99