Challenges arise when working with multiple promises while attempting to retrieve download URLs from Cloud Storage

My goal is to save each downloadURL from multiple promises (files being uploaded) in an array while iterating through them. However, what's happening is that I only get the first output for every item, regardless of how many items I upload. It keeps giving me the first downloadURL from the first promise.

If there was a way to label each promise so they don't overlap and give me the same value for each file, or perhaps pause each one and wait for the first one to finish before starting the next one. The first solution seems more appealing to me, but I'm still unsure how to implement it.

   pushUpload(upload: Upload) {

    let storageRef = firebase.storage().ref();
    this.uploadTask = storageRef.child(`${this.basePath}/${upload.file.name}`).put(upload.file);

    this.uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
      (snapshot) =>  {
        // upload in progress
        upload.progress = Math.ceil((snapshot.bytesTransferred / snapshot.totalBytes) * 100)
      },
      (error) => {
        // upload failed
        console.log(error)
      },
      () => {
        // upload success
        this.uploadTask.snapshot.ref.getDownloadURL().then((url)=>{
          this.uploadInfo.push(url)
        })
      })
  };
  uploadMultiple() {
    let files = this.selectedFiles
    let filesIndex = _.range(files.length)
    _.each(filesIndex, (idx)=>{
      this.currentUpload = new Upload(files[idx]);
      this.service.pushUpload(this.currentUpload);
    })
  }

Answer №1

If you want to transform your Promises into Observables, RxJS can help with that. By using forkJoin, you can wait for each Promise to complete.

import { from, forkJoin } from 'rxjs';

let promises = thePromiseArray();
forkJoin(...promises.map(promise => from(promise))).subscribe(
  results => {
    console.log("Here is an array of results from each Promise:", results);
  }
)

Additionally, you can utilize pipe to incorporate extra operators for all downloads, or target specific downloads individually. For instance, you could apply timeout to ensure a maximum waiting time:

forkJoin(...promises.map(promise => from(promise).pipe(
  timeout(25000) // This will be applied to each download separately
))).pipe(
  // Any additional operators here will affect the entire forkJoin operation
).subscribe(
  results => {
    console.log("Array of results from each Promise:", results);
  }
)

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

Exploring the functionality of Angular's Material Virtual Scroll and incorporating the scrollToIndex method

Is there a way to manage the scrollToIndex (virtual scroll) if my list is not loaded during the ngAfterViewInit lifecycle? I need to trigger the scroll to a specific index when redirecting from another page, which happens in the ts file. My objective is to ...

Angular data binding with an object instead of an array list

Currently, I am implementing Angular and attempting to iterate through an object. Data in JSON format employee {"fName":"mike","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ebb3b3b3b3b3b3b3b3ab83849f868a8287c588848 ...

Building SVG components in React with TypeScript and styling them using SCSS

I've been experimenting with using Webpack to import SVG files as components in React Typescript. However, I'm running into trouble when it comes to styling the SVGs with SCSS. I've tried targeting a custom attribute in my CSS selector, but ...

The problem with the "typescript-react-apollo" codegen plugin is that it is declaring block-scope variables more than once in the generated

Recently, I embarked on a new project utilizing NextJS with graphql-codegen to auto-generate my apollo-react types from the API. Unfortunately, it seems to be generating duplicate exported variables right from the start, causing a typescript error and hi ...

Angular findIndex troubleshooting: solutions and tips

INFORMATION = { code: 'no1', name: 'Room 1', room: { id: 'num1', class: 'school 1' } }; DATABASE = [{ code: 'no1', name: 'Room 1', room: { id: 'num1', ...

Socket.emit allows for the transmission of various data points

Can someone help me with an issue I'm facing regarding socket.emit inside socket.on concatenating the same value after every emitting? Below is the code snippet on the server-side: io.on('connection', function(socket){ let balance = 6000; ...

JavaScript and Angular are used to define class level variables

Hello, I'm currently diving into Angular and have encountered an issue with a class level variable called moratoriumID in my component. I have a method that makes a POST request and assigns the returned number to moratoriumID. Everything seems to work ...

The HttpEvent containing Observable of State arrays is not compatible with the type Observable of State arrays

My Angular app fetches state information from a REST API and showcases it on the website. In my state component, I invoke the state service, which in turn communicates with the backend using the httpClient.get() method. When passing parameters from the com ...

The error you are seeing is a result of your application code and not generated by Cypress

I attempted to test the following simple code snippet: type Website = string; it('loads examples', () => { const website: Website = 'https://www.ebay.com/'; cy.visit(website); cy.get('input[type="text"]').type(& ...

Comparison between typings and @types in the NPM scope

There are different approaches when it comes to handling TypeScript definitions. In some cases, the typings tool is used, as seen in projects like angular/angular2-seed. Alternatively, some projects use scoped NPM packages with the prefix @types, complete ...

ng-pattern is not throwing any errors

After spending hours on this issue, I realized it was time to seek help here. I have been struggling with setting up an input field that displays a specific message when someone tries to type in a number. My extensive research brought me to ng-pattern as ...

get a collection of chosen files in angular 7 and save them to

Greetings, I am currently working on a project and encountering an issue. I need to download multiple selected files from a list, but despite my efforts in searching for a solution, I have been unable to find one. While I can successfully download single f ...

Unlocking the power of asynchronous methods within the useEffect() hook

When attempting to fetch an API within a useEffect(), I encountered the following error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Here is the code snippet that caused the error: -API being fetched: ex ...

It appears that TypeScript is generating incorrect 'this' code without giving any warning

I seem to be facing some resistance filing a feature request related to this on GitHub issues, so I'll give it a shot here. Here is the code snippet that caused me trouble: export class Example { readonly myOtherElement: HTMLElement; public ...

utilize console.log within the <ErrorMessage> element

Typically, this is the way the <ErrorMessage> tag from Formik is utilized: <ErrorMessage name="email" render={(msg) => ( <Text style={styles.errorText}> ...

Modify the Subform element based on the chosen option in the dropdown menu

I am working on a reactive form that includes a select element. Depending on the selected value, different subforms should be displayed. Each subform has its own form group. I have successfully implemented the functionality to show the different subforms a ...

Issue with TypeScript: Error appears when importing express after running "npm i @types/express -D"

Struggling with adding the following line of code in an index.ts file: import express, { Application } from 'express'; Initially encountered an error with "from 'express'", so I ran npm i @types/express -D which fixed that is ...

Leveraging ngIf and ngFor within choice

Is there a way to combine ngIf and ngFor in a single line of code? Here is the code snippet I am currently using: <option *ngIf="tmpLanguage.id!=languages.id" *ngFor="let tmpLanguage of languages" [ngValue]="tmpLanguage.id"> {{tmpLang ...

Generate dynamic property values based on calculations

I am facing a challenge with a form that I have designed. Could you guide me on how to dynamically update the value of the calculate field (contingency) whenever the user modifies the values of budget1 and budget2? I have attempted several approaches witho ...

Angular CLI produced the Git command

After starting a project with the Angular CLI, I know it should create a git for me. I typed the following commands in my project directory: git add . git commit -m "some message" Now I want to push. Where do I push this to? Or where is the GitHub r ...