Tips for ensuring all data is downloaded in Firebase (Firestore) Storage before proceeding?

I am currently developing a light dashboard in Vue that connects to Firestore and Storage. As someone who is not an expert, I have encountered a roadblock in what should be a simple task. The issue lies with a function that is meant to retrieve all URLs based on filenames from the storage system.

getImages: function(uid, images) {        
    images.forEach((filename) => {
        var ref = firebaseApp.storage().ref('images/' + uid + "/" + filename);
        ref.getDownloadURL().then(function(url) {   
          this.finalImages.push(url)
          console.log(url);
        }).catch(function(error) {
            switch (error.code) {
                case 'storage/object_not_found':
                    // File doesn't exist
                    console.log('Object not found');
                    break;

                case 'storage/unauthorized':
                    // User doesn't have permission to access the object
                    console.log('You do not have the right permissions');
                    break;

                case 'storage/canceled':
                   // User canceled the upload
                    console.log('Canceled');
                    break;

                case 'storage/unknown':
                     // Unknown error occurred, inspect the server response
                    console.log('Who knows...');
                    break;
            }
        })
    })
}

However, the URLs download after the code execution finishes, making them invisible to me. Is there a way to pause the process until the URLs populate the finalImages array before continuing?

Answer №1

To efficiently handle multiple asynchronous requests, you can map each request to a promise and then wait for all promises to complete:

retrieveImages: function(userID, imageList) {        
  Promise.all(imageList.map((imageName) => {
    return new Promise((resolve, reject) => {
      var reference = firebaseApp.storage().ref('images/' + userID + "/" + imageName);
      reference.getDownloadURL().then(function(url) {
        resolve(url);
      }).catch(function(error) {
        // Uncomment the next line to ignore errors.
        reject(error);
        switch (error.code) {
          case 'storage/object_not_found':
            // The file doesn't exist
            console.log('Object not found');
            break;

          case 'storage/unauthorized':
            // User lacks permission to access the object
            console.log("You don't have the necessary permissions");
            break;

          case 'storage/canceled':
            // Upload was canceled by the user
            console.log('Canceled');
            break;

          case 'storage/unknown':
            // Unknown error occurred, check server response
            console.log("Unknown error... what's going on?");
            break;
        }
      })
    });
  })).then((allImages) => {
    // Handle all retrieved images here.
  })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can the entire menu be closed in Bootstrap 5 when clicking on a link or outside of the page?

I'm currently utilizing BootStrap 5 for constructing my webpage. Within my page, I have a NavBar Menu containing various links. <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Is it true that event.stopPropagation does not function for pseudoelements?

I am facing an issue with event handling in my ul element. The ul has three li children elements, and the ul itself has a useCapture event handler for click. In the click event handler, I successfully stop the event using event.stopPropagation(), and every ...

The custom tab component in React is currently not accepting the "disabledTabs" prop

I have designed a tab component as shown below: tab/index.jsx import React from 'react'; import TabHeader from './header'; import TabBody from './body'; import TabHeaderList from './header/list'; import TabBodyList ...

Is it necessary to have n_ if I've already set up lodash?

After some research, I came across a recommendation to install lodash. However, upon visiting the lodash website, they suggest that for NodeJS, n_ should be installed instead. Are both necessary? Is one more comprehensive than the other? Do I even need eit ...

Gather every hyperlink and input fields without utilizing jQuery

Is there a way to target all a and form elements without relying on jQuery? My end goal is to achieve the following functionality: document.querySelectorAll('a').forEach(element => { element.addEventListener('click', () => { ...

Encountering a 404 error when translating URLs in Next.js i18n?

I am developing a multilingual service utilizing next-i18next. I wanted to have some of my routes translated as well, for example: EN: /contact => default language IT: /fa/ارتباط-با-ما => second language To achieve this, I utilized tran ...

Is it possible to use an angular expression as the ng-click function?

I have been searching everywhere for the answer to this question. Within my code, there is an angular object called column.addOnParams. This object includes a child element named rowClick, which can be accessed using column.addOnParams.rowClick. The val ...

What steps can I take to identify and manage a browser's inability to play a media file?

I am currently utilizing a JavaScript utility to stream mp3 content. Unfortunately, there are instances where I direct users to a file that cannot be played due to external factors. In such cases, Firebug displays an error message indicating that the file ...

The issue of JQuery Mobile not recognizing HREF links when combined with Javascript

I am facing a challenge with my button functionality that is supposed to open a panel. However, there seems to be an interference caused by my JavaScript code. The panel contains a notifications center and in order to retrieve the notifications, I have to ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

Determine the presence of an image by using a wildcard in the URL

I need to show an image, and if it doesn't exist I want to display a default image. The challenge is that the image can come with any extension. Can someone suggest how I can modify the $.get() function in the code snippet below to make it search for ...

What are the similarities between using the map function in AngularJS and the $map function in jQuery?

I am currently in the process of migrating jQuery code to AngularJS. I have encountered some instances where the map function is used in jQuery, and I need to replicate the same functionality in AngularJS. Below is the code snippet that demonstrates this. ...

Programmatically Expand and Collapse All nodes in MUI DataGrid using ReactJS

Is there a way to programmatically expand or collapse all rows in MUI ReactJS DataGrid? What have I tried? I attempted to use the defaultGroupingExpansionDepth property as suggested in the MUI documentation: export const EXPAND_ALL = -1; export const COLL ...

``When you click, the image vanishes into thin

Could you please explain why the image disappears once I close the lightbox? Access with password: chough ...

Encountering issues with jQuery AJAX POST request

I'm currently facing an issue while attempting to send a post request to parse JSON formatted data into my webpage. Here's an example of the query: $("#click").click(function () { $.ajax({ type: "POST", url: "http://ut-pc-236 ...

Show only the image source (img src) and do not display the audio and video sources using jQuery

In my code, I need the following conditions to be met: when an image is posted from the backend, the video and audio sources should automatically hide; when a video is posted, the image and audio sources should hide; and when an audio file is posted, the v ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

Error message "Vue CLI project setup encountering ENOENT error: file or directory does not exist"

I'm currently in the process of creating a new Vue.js app, and I've executed the following command: vue create client After that, I opted for the default template: default (babel, eslint) However, during the setup process, it abruptly stops w ...

The JQuery .replaceWith method exclusively offers unprocessed HTML content

I'm experiencing a minor issue with my ajax response where it returns raw html and does not execute any scripts, resulting in the jquery ui scripts not being executed. Here are some details: I am currently working with ASP.NET MVC and I need to comm ...

A step-by-step guide on recompiling Vue using shell_exec()

I am facing an issue with my Vue application that is supposed to receive updates via webhook.php. In this setup, there is a PHP script responsible for updating internal configurations. The problem arises at the end of the webhook.php file where I have incl ...