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

Utilizing Express 4, create a fresh route within an app.use middleware

I'm currently working on an express nodejs app where I am attempting to implement "dynamic routes" within another route. Here is what I have: .... app.use('/test/:id', function(req,res,next) { app.use('/foo', sta ...

Using Webix in conjunction with Vue.js to make method calls

Is there a way to invoke the method storeNewOrder in the onAfterDrop event from the Webix component? Neither this.$emit.storeNewOrder() nor storeNewOrder() seem to be effective. export default { template:"<div></div>", pro ...

Error when spaces are present in the formatted JSON result within the link parameter of the 'load' function in JQuery

I am facing an issue with JSON and jQuery. My goal is to send a formatted JSON result within the link using the .load() function. <?php $array = array( "test1" => "Some_text_without_space", "test2" => "Some text with space" ); $json = jso ...

What is the most effective method to update the interface following the addition of item data to the database?

How can Vue.js refresh the interface after adding a new strip of data to the backend database? When an item is added to the database, there are two options for refreshing the interface: Refresh the list API to retrieve the updated page data. Add the new ...

PHP - Implementing a Submit Button and Modal Pop-up AJAX across multiple browsers in PHP

As a newbie in PHP AJAX coding, I'm facing a challenge with having two browsers. My goal is to click the submit button on one browser and have a modal popup on the other browser simultaneously. Essentially creating a chat system where only a button an ...

What is the best way to trigger a Quasar dialog from an outside component?

Currently, I am working with Vue.js 2.x + Quasar 1.x using http-vue-loader (no build tools required). I have placed a q-dialog in a separate component named MyComponent. However, when I try to include it in a parent component like this: <my-component&g ...

Using VueJS to dynamically add a CSS class if a certain filter is

Can you apply this filter rule in VueJS? If an element has the filter discount, the parent will be styled with the class color-green (in this case, the span tag) Check out my JSFIDDLE for more details :) HTML <div id="app"> <h3>50% Disc ...

Exploring the power of d3 in Vue through force-graph integration

I am currently working with force-graph in a Vue project. I have installed force-graph using npm and imported ForceGraph into a single-file Vue component. However, when attempting to use the following code for a ForceGraph Graph Graph.d3Force("link",d3.for ...

The nth-child selector fails to function properly with a customized MUI component in CSS

I've created a styled component as shown below: const FormBox = styled(Box)(({ theme }) => ({ width: "47vw", height: "25vh", backgroundColor: theme.palette.grey[100], borderRadius: theme.shape.borderRadius, marginLeft: ...

Error message: The method app.get() is invalid as it is not a

I'm having trouble using Express in a prototype function ioServer() { } module.exports = ioServer; ioServer.prototype.start = function() { var app = require('express') var http = require('http').Server(app) ...

What steps should I take to incorporate the delete feature as described above?

Click here to access the delete functionality Hello there, I need help implementing a delete function similar to the one provided in the link above. Below is the code snippet for your reference. I am utilizing the map method to extract data from an array ...

Attaching dynamic data to a specific element within an array

I have successfully created a demo where elements can be dropped into a specific area and their top and left values are displayed. I have also added functionality to remove dropped items and move them between different blocks. However, I am encountering so ...

Exploring the PayPal Checkout JavaScript SDK's CreateOrder call and interpreting the response

I am currently exploring how to use the JavaScript SDK to display PayPal payment buttons on a website. I am new to working with JSON and REST API calls, so I am facing some challenges in implementing this. The createOrder function is running smoothly and ...

Tips for avoiding the persistence of an old array on the screen after refreshing and showing the new, updated array

Currently, my task involves displaying array values on a webpage. The array data is sourced from a real-time database in Firebase. After adding new values to the array or inputting another value into the database on the previous page, we are redirected to ...

After the jquery.show function is executed, an unexpected WebDriverException occurred, indicating an unknown error that prevents focusing

Here is my line of JavaScript code: $('#name').show(); And this is my webdriver code line: wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("name"))).sendKeys("Some Name"); When running the test, I encountered an exception: Web ...

Storing JSONP data in a variable: Tips and Tricks

Having an issue with storing JSONP data into variables and using it as input for a Google Pie Chart. Consider the following: Data in test.json: { "name": "ProjA", sp": 10, "current": 20 } The goal is to retrieve the SP value. Attempted solution usin ...

Retrieving custom data attributes from slides within a slick carousel

After the recent Slick carousel update to version 1.4, there have been changes in how data attributes are accessed from the current slide. The previous method that was working fine is as follows: onAfterChange: function(slide, index) { $('.projec ...

Install the npm package if there have been modifications to the package.json file

In short: Can we make npm install run automatically before executing any npm script if the package.json file has been modified? Situation Summary Imagine you switch to a branch that has updated the package.json file. You try running npm run my-script, bu ...

Adding rows to a Datatable using an object array in rows.add()

Attempting to refresh my current Datatable by fetching new data using an Ajax function. Despite trying various solutions from other sources, the table does not update as expected. The function being used is shown below: $.ajax({ url: "<?php echo s ...

The issue persists with setState not functioning correctly and the checkboxes for filtering not registering as checked

I am currently in the process of developing a simple ecommerce platform which focuses on shoe shopping. Users will be able to search for shoes and apply filters based on brand and type. Here's where I stand with my progress: Clicking on filter check ...