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?

3

2 Answers 2

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")})
Sign up to request clarification or add additional context in comments.

2 Comments

Is Promise.all native to JS? No Libraries? @jdubjdub mentions bluebirdJS.
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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.