Rafay Rafay - 1 month ago 8
Javascript Question

Order of array after async activity

I have the following piece of code that hits an API to upload an array of images and return their links in an array; however, the order in which the images are uploaded is not honored.

if (req.files) {

var uploadedImages = [];

for (var i = 0; i < req.files.length; i++) {
imgur.uploadFile(req.files[i].path)
.then(function (json) {
uploadedImages.push(json.data.link);
if (uploadedImages.length === req.files.length) {
console.log(uploadedImages);
//Further processing
}
})
.catch(function (err) {
console.log("Imgur API Error!");
console.log(err.message);
res.redirect('/participants?err=' + encodeURIComponent('An unknown error occured. Please try again.'));
});
}


So for example, if I upload 1.jpg, 2.jpg, and 3.jpg, the array holding the respective links for these images is not necessarily in the same order. What is the best way to ensure that the order is not compromised during this async activity?

Answer

Use Promise.all to convert an array of promises into a promise of an array:

var uploads = req.files.map(function (file) {
  return imgur.uploadFile(file.path)
    .then(function (json) {
      return json.data.link;
    });
});

Promise.all(uploads)
  .then(function (uploadedImages) {
    console.log(uploadedImages);
    // Further processing
  })
  .catch(function (err) {
    console.log("Imgur API Error!");
    console.log(err.message);
    res.redirect('/participants?err=' + encodeURIComponent('An unknown error occured. Please try again.'));
  });