JavaScript maintaining records and connections between multiple asynchronous events

I am working on an Angular 10 project where users can compress and upload images to Google Cloud Storage. The compression and uploading functionalities are functional, but I'm facing challenges with managing the asynchronous process of handling multiple compressions and uploads at once.

What would be the most effective approach to monitor the progress of each file during compression and upload?

I believe using a class variable like an Array of objects would be ideal for displaying the progress to the user.

One potential solution could be pushing an object to a class Array, but how can we keep track of the specific element to update its status after compression is completed and trigger the percentageChanges() observable when the upload begins?

In my code snippet below, the processFileList() function is called when a user submits selected images through an HTML file input:

 async compressAndUpload(file) {
   // Compress image - function details not provided, returning a promise
   const compressed = await compressImage(file);

   // Create upload path
   const uploadPath: string = 'file' + (new Date()).getTime()
   
   // Upload the compressed image
   const imageUploadTask = this.storage.upload(uploadTask, compressed)
   
   // Obtain current upload percentage as an observable
   const percentage = imageUploadTask.percentageChanges()
}


processFileList(fileList: FileList) {
    // Convert FileList to array for iteration
    const files = Array.from(fileList);
    
    // Iterate through each file and call compressAndUpload function
    files.forEach(file => {
        compressAndUpload(file);
    })
   
}

Answer №1

For effective progress tracking, it is recommended to utilize full observables, especially when working within the Angular framework where familiarity with rxjs is essential:

import { merge, from } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
//...
function compressAndUpload(file) {
   // ... set up uploadTask

  return from(compressImage(file))// It's preferable to convert the returned result to an observable or cast it using from
    .pipe(
      switchMap((compressed) =>
        this.storage.upload(uploadTask, compressed).percentageChanges()
          .pipe(
            map(progress => ({ file, progress }))
          )
      )
    )
}


function processFileList(fileList: FileList) {
  // Convert the FileList into an array for iteration
  const files = Array.from(fileList);

  return merge([...files.map(compressAndUpload)])
}

processFileList(someFileList)
  // Implement a progress reporter upon subscription
  .subscribe(({ file, progress}) => console.log('Progress', progress, 'for file', file))

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

Tips for interpreting JSON information and showcasing it with the assistance of Ajax in JQuery?

There's a request made to the system via AJAX that returns JSON as a response, which is then displayed in an HTML table. The HTML code for displaying the data looks like this: <table id="documentDisplay"> <thead> <tr ...

What is the best way to connect Classes and Objects in Angular5?

Picture a study tool with flashcards and different categories. Each category has a title, while each card contains content, is linked to only one category, and is also connected to another card. How can I establish these connections in Angular 5 and Types ...

Checkbox selection limitation feature not functioning correctly

Having trouble with my checkbox question function - I want to limit the number of checkboxes that can be checked to 3, but it's still allowing more than that. I suspect the issue lies with latestcheck.checked = false; This is my typescript function: ...

Troubleshooting: Style sheets not loading on a page rendered by node

Today was my first attempt at learning Node.js and creating a basic server to display a single page with a header tag. However, I encountered an error stating that the CSS file could not be loaded. This is the code I used: const express = require('ex ...

Produce configuration files on the fly for Angular Component Testing using @Component declarations

Looking to test an Angular 11 component: @Component({ selector: 'app-foo-page', template: ` <app-header mode='operational' cool='true'></app-header> Some content ` }) export class FooPageComponent { } ...

Validate if cookie has been established in Javascript

Hello everyone! I am trying to redirect a user to another page when a cookie is set by clicking a button. <a href="" onClick="SetCookie('pecCookie','this is a cookie','-1')"><button type="button" name="accept" clas ...

What is the best way to retrieve state within a property of a React class component?

I have encountered an issue with a React Class Component where I am trying to separate a part of the rendered JSX but unable to access the Component's state within the separated JSX as a property of the class. The scenario is quite similar to the fol ...

Failed to cast value "undefined" to ObjectId in the "_id" path for the model "User"

I've been encountering an issue that I can't seem to resolve despite searching on Stack and Google. My ProfileScreen.js is meant to display a user's profile, but when attempting to view the profile, I receive this error: "Cast to ObjectId fa ...

Angular2 - Breaking down applications into reusable components

Utilizing custom properties permits seamless data binding between multiple components. <section id="main"> <app-home [dict]="dict">Hello there!</app-home> </section> In this scenario, dict serves ...

What is the process of creating a new array by grouping data from an existing array based on their respective IDs?

Here is the initial array object that I have: const data = [ { "order_id":"ORDCUTHIUJ", "branch_code":"MVPA", "total_amt":199500, "product_details":[ { ...

Is there a method to access a website, trigger JavaScript functions, and subsequently retrieve the HTML content using PHP?

I am currently exploring options to access a webpage, execute JavaScript functions on it (thus altering the HTML content), and eventually save the modified version of the page. I'm uncertain if this approach is feasible, and if not, are there alternat ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Encountering an error with unexpected token in jsdom while utilizing babel and npx

I am looking to perform canvas tests exclusively in node.js. Here is my package.json { "name": "test", "description": "Test", "version": "0.1.0", "author": "anthony@work", "dependencies": { "canvas": "^1.6.7", }, "devDependencies": { ...

Can you please explain to me how to target a specific element by its ID in the DOM and then move on to the next element with the same ID using jQuery

During the event handling process, a scenario arises where two div elements end up having identical IDs within the DOM structure. While using JQuery, my objective is to specifically target the second occurrence of the div with the aforementioned ID in the ...

Error in parsing: An unexpected symbol appeared, an identifier or keyword was expected at the end of the expression

Whenever I attempt to display data from an API, an error always pops up. My goal is to showcase each piece of data individually. To help you analyze the issue, I've included the URL of the API below: civilizationes.component.ts import { Component, O ...

What is the method for automatically scrolling down while hovering over an image?

How can I make it so that when an image is hovered over, it automatically scrolls to the bottom of the image? I have a couple of questions: How can I ensure the image scrolls to the end when hovered over? Currently, when I hover over the image, it doe ...

Guide on utilizing $q for retrieving a promise from a $broadcast within angularJS

Currently, the controller code I've written is structured like so: $scope.spAPI.load(id).then(function(result){ var deferred = $q.defer(); if(result !== undefined){ deferred.resolve($rootScope.$broadcast("onSpLoaded", result)); } return de ...

Autocomplete failing to provide a valid response, returning a null value instead

Utilizing an Autocomplete feature for employee search, users can input a name and select from the list of results. However, the current onChange function logs the index value instead of the selected employee's name. Is there a way to pass the employee ...

"In the realm of RxJS, there are two potent events that hold the power to

In my current situation, I encountered the following scenario: I have a service that makes Http calls to an API and requires access to user data to set the authentication header. Below is the function that returns the observable used in the template: get ...

Stop committing changes in Git when there are any TypeScript errors found

While working on my project in TypeScript using Visual Code, I encountered a situation where I was able to commit and push my changes to the server through Git (Azure) even though there was an error in my code causing a build failure. It made me wonder i ...