cbdeveloper
cbdeveloper

Reputation: 31485

Javascript async how to await for a varying number of uploadTasks to all be completed?

I have saveBlogPost() function that needs to perform the following actions:

My question is how to wait for a varying number of uploads?

Here is my code so far:


savePost() function:

function savePost() {
  uploadImages();
}

uploadImages() function:

Note: images is an array of the image files to be uploaded.

function uploadImages() {
  images.forEach((image) => {
    const uploadTask = storageRef.put(file,metadata);
    uploadTask.on('state_changed',
      function progress() {
        //UPLOAD PROGRESS BAR
      },
      function error(err) {
        //SET ERROR
      },
      function complete() {
        //UPDATE IMAGE URL IN BLOGPOST OBJECT
        //SET COMPLETE
      }
  });
}

QUESTION:

My intent is to make savePost() function async and await for the uploadImages() function. But how can I resolve/reject the uploadImages() function only after ALL the images have resolved/rejected ?

Something like:

async function savePost() {
    const result = await uploadImages();
    // ACT BASED ON RESULT
  }

But I don't know what to do with the uploadImages() function in order to resolve/reject only after all the images are done.

How can I do this?

Upvotes: 0

Views: 133

Answers (2)

Aleksandr Yatsenko
Aleksandr Yatsenko

Reputation: 869

function uploadImages() {
    const promises = images.map(async image =>
        new Promise((resolve, reject) => {
            const uploadTask = storageRef.put(file, metadata);
            uploadTask.on('state_changed',
                function progress() {
                    //UPLOAD PROGRESS BAR
                },
                function error(err) {
                    //SET ERROR
                    reject(err);
                },
                function complete() {
                    //UPDATE IMAGE URL IN BLOGPOST OBJECT
                    //SET COMPLETE
                    resolve();
                }
            );
        })
    );

    return Promise.all(promises);
}

Upvotes: 4

Gaurav Punjabi
Gaurav Punjabi

Reputation: 153

A forEach loop will not work for async / await as you would like it to work.

Try using a simple for loop:

for(let i = 0; i < n; i++){
    let response = await savePost();
}

Upvotes: 1

Related Questions