0

Currently, my code loads all images async. That also means in my current implementation that the image is added to the fileArray once it has been completely downloaded. Since not all images are equal in size, downloads of each image finish at different times, resulting in the images being added to the array in a random order.

How can I force images to be added to the file array in the order their downloads start ? Hopefully without giving up the benefit of async (all images being downloaded at the same time).

for (var i = 0; i < imageArray.length; i++) {
            imageArray[i].download(function(err, contents) {
                fileArray.push(base64_encode(contents));
                console.log("SIZE: "+fileArray.length);
                if (fileArray.length == 9) {
                    res.render("home", {keyArray: keyArray, titleArray: titleArray, usernameArray: usernameArray, imageArray: fileArray});
                }
            });
        }
TheProgrammer
  • 1,409
  • 4
  • 24
  • 53

1 Answers1

3

You can use Promises and map the async callbacks to a Promise.all():

Promise.all(imageArray.map(function(image) {
    return new Promise(function(resolve, reject) {
        image.download(function(err, contents) {
            if (err) {
                reject(err);
            } else {
                resolve(base64_encode(contents));
            }
        });
    });
})).then(function(fileArray) {
    res.render("home", {keyArray: keyArray, titleArray: titleArray, usernameArray: usernameArray, imageArray: fileArray});
}).catch(function(err) {
    // uh oh
});

Bonus is you don't need to check the array size to confirm completion.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • Bingo. That worked brilliantly. I find quite funny that almost everytime I get stuck on a coding problem in web dev, it's because I don't understand well enough Promises. Would you have a link to recommend ? – TheProgrammer Jun 19 '17 at 19:29
  • The two in my answer have all the documentation I feel I ever needed to know. I just forced myself to start using them, since I was tired of installing and using [async](https://github.com/caolan/async). It's a good library, but there are too many functions to keep up with. Promises are much more simple and consistent. – Patrick Roberts Jun 19 '17 at 19:31
  • I didn't see those were links ^-^ Great ! Thx – TheProgrammer Jun 19 '17 at 19:33
  • Hi ! I am stuck again on a very similar issue. Could you please have a look ? https://stackoverflow.com/questions/44654810/why-is-the-order-of-the-downloaded-images-not-maintained – TheProgrammer Jun 20 '17 at 13:44