1

So in my app the user is able to upload 1 to 3 pictures and when he hits the save button I upload them to firebase.

This is my code so far and I know it is horrible and I am looking for a way to make it efficient.

    if (img1) {
      uploadImage(img1, 'image/jpeg', 'imageOne', uuid)
      .then(() => {
        console.log('Image 1 was uploaded succesfully');

      }).catch(err => console.log(err));
    }

    if (img2) {
      uploadImage(img2, 'image/jpeg', 'imageTwo', uuid)
      .then(() => {
        console.log('Image 2 was uploaded succesfully');

      }).catch(err => console.log(err));
    }

    if (img3) {
      console.log('there is img3')
      uploadImage(img3, 'image/jpeg', 'imageThree', uuid)
      .then(() => {
        console.log('Image 3 was uploaded succesfully');

      }).catch(err => console.log(err));
    }

The thing is that I want to redirect the user to the home page when the upload finishes. But it is hard to decide where the redirect-code should go.

I thought about doing nested if statements like so:

if (img1) {
      uploadImage(img1, 'image/jpeg', 'imageOne', uuid)
      .then(() => {
        console.log('Image 1 was uploaded succesfully');

        if (img2) {
          uploadImage(img2, 'image/jpeg', 'imageTwo', uuid)
          .then(() => {
            console.log('Image 2 was uploaded succesfully');

          }).catch(err => console.log(err));
        }


      }).catch(err => console.log(err));
    }

but what If the user uploaded just img2 and not img1? Then img2 would never be uploaded. How can I improve my code?

Walter Monecke
  • 2,386
  • 1
  • 19
  • 52
  • This has been asked a lot here, please search the archives for async javascript and you'll see a multitude of answers. In a nutshell, use this: https://caolan.github.io/async/ – Graham Aug 09 '17 at 16:49
  • Please see that solution: https://stackoverflow.com/questions/13912775/jquery-deferred-getting-result-of-chained-ajax-calls/13913059#13913059 – Zim84 Aug 09 '17 at 16:50
  • Possible duplicate of [Async JavaScript Callback](https://stackoverflow.com/questions/27864294/async-javascript-callback) – Graham Aug 09 '17 at 16:50

2 Answers2

2

You can use Promise.all

let promises = [];
if (img1) {
    promises.push(uploadImage(img1, 'image/jpeg', 'imageOne', uuid);
}
if (img2) {
    promises.push(uploadImage(img2, 'image/jpeg', 'imageTwo', uuid);
}

// etc...

Promise.all(promises).then(() => {console.log("All requests are done")})
user184994
  • 17,791
  • 1
  • 46
  • 52
1

check out Promise.all - Bluebird is a good library for promises, though native is totally cool too now. http://bluebirdjs.com/docs/api/promise.all.html

would look something like this:

var p = [];

if (img1) p.push(uploadImg(img1...));
if (img2) p.push(uploadImg(img2...));
if (img3) p.push(uploadImg(img3...));

return Promise.all(p).then(function() {
    // redirection here
});
jdubjdub
  • 613
  • 7
  • 21