Leveraging the power of TypeScript and Firebase with async/await for executing multiple

Currently, I am reading through user records in a file line by line. Each line represents a user record that I create if it doesn't already exist. It's possible for the same user record to be spread across multiple lines, so when I detect that it has already been created, I simply skip over it.

The code snippet I'm using is shown below:

async onFilesAdded(files: FileList){
    this.fileToUpload = files.item(0);

    let fileReader = new FileReader();
    fileReader.onload = async (e) => {
     this.showProgress = true
      var lines = fileReader.result.toString().split(/[\r\n]+/g); // handling both Windows and Unix linebreaks
      this.totalLines = lines.length
      var firstLine = false

      this.dcSvc.getPageImages().then(
        (resp) => {
          console.log("resp in getPageImage" + JSON.stringify(resp))
          this.pageMap = resp
          this.lineCount = 0
          for(let line of lines){
            if(firstLine == false){
              firstLine = true
            }else{
               this.createClickHistory(line).then(
                 (resp)=> console.log("line processed")
               )
            }
          }
        }
      )
    }

    fileReader.readAsText(this.fileToUpload);
}

async createClickHistory(line:string){
        var lineArr = line.split(',')
        const userName = lineArr[1]

           this.dcSvc.getUser(userName).then(
             (res:any) => {
                         console.log("Response of get user is:::" + JSON.stringify(res))
                         if(res.length == 0 ){
                           //user does not exist in the DB
                           console.log("user:" + userName + " does not exist so creating it")
                           const userPayload = {
                                                 "userName": userName
                                               }

                                               this.dcSvc.createUser(userName, userPayload).then((rsp) => {})

                         }else{
                           //user exists so skip
                        }
                })
}

createUser(userName:string, userPayload){
        return this.db.object("/users/" + userName).set(userPayload)
      }

getUser(userName:string){
        return new Promise((resolve, reject) => {
                  this.db.list('/users', 
                      ref => ref.orderByChild("userName").equalTo(userName)
                  ).snapshotChanges().subscribe(
                    (res) =>  {
                                resolve(res)
                              }
                  )
                })

      }

It seems that the current code doesn't wait for each line to process before moving on to the next one. As a result, I have to run the code multiple times to ensure all data is imported correctly.

Answer №1

To add a delay to your line reading process, you can utilize a timeout:

 let timer = 0;
 for (let currentLine of lines){
   if (firstLine == false){
     firstLine = true;
   } else{
     setTimeout(function(currentLine){ this.createClickHistory(currentLine).then(
       (response)=> console.log("line processed")
     )}.bind(this, currentLine), timer*16) // Running at 60 frames per second
   }
   timer++
 }

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 saving metadata about properties within a class

I am looking to add metadata to properties within classes, specifically using abbreviations for property names. By using annotations like @shortName(abbreviated), you can label each property as follows: function shortName(shortName: string){ return fu ...

Troubleshooting issue with problemMatcher in VSCode TypeScript compiler not functioning

I am looking for a problem matcher that can detect two types of issues: compilation problems related to TypeScript issues flagged by tslint This feature seems to be causing trouble in one of my projects, although it functions properly in others. Below i ...

Tips on how to access the names of all properties within a TypeScript class while excluding any methods

Looking to enhance the reactivity of my code, I want to render my view based on the properties of a class. How can I extract only the property names from a class and exclude methods? For instance: export class Customer { customerNumber: string; ...

Issues with data not flowing through in Rebase/Redux/Firebase integration with React

Currently attempting to synchronize a table of data from Firebase 3.x.x with my React application. This library seems to be the most popular choice for this task. See below for the code with placeholders filled in. App.js: componentDidMount() { var bas ...

Enhance Component Reusability in React by Utilizing Typescript

As I embark on developing a React application, my primary goal is to keep my code DRY. This project marks my first experience with Typescript, and I am grappling with the challenge of ensuring reusability in my components where JSX remains consistent acros ...

Having trouble incorporating @types/pdfmake into an Angular project

I have been experimenting with integrating a JS library called pdfmake into an Angular application. I found some guidance on how to accomplish this at https://www.freecodecamp.org/news/how-to-use-javascript-libraries-in-angular-2-apps/, which involved usin ...

Discovering the breakpoints for Angular ng-bootstrapUncover the angular ng

Utilizing ng-bootstrap in my latest project has allowed me to easily create a grid with breakpoints, like so: <div class="row"> <div class="col-sm-12 col-md-6 col-xl-4"></div> </div> Although these breakpoints are convenient, ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

What is the reasoning behind TypeScript's decision to permit the omission of a function's return type?

After setting noImplicitAny to true in my tsconfig, I was surprised to find that I could still omit function return types. One instance is a getter function as shown below: get name() { return `${this.valueName} of ${this.suitName}`; } Inquiry 1: Can ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

Identify the CSS class for the ionic component on the webpage

Currently, I am in the process of developing an application using ionic 2 and angular 2. Within this app, I am utilizing the ionic 2 component known as ModalController. Unfortunately, I have encountered a challenge when attempting to adjust the size of th ...

Securing access with AngularJS, Firebase, and Google App Engine: User verification and approval

As a newcomer to web development, I must admit that my question may come across as basic. However, after spending the last 3 hours researching how to address what seems like a common issue, I am still unsure about whether my grasp of the concept is accurat ...

` Detecting initialized properties of classes using Eslint rule`

When useDefineForClassFields:true is used, the code below becomes invalid when targeting es2022: Cannot read properties of undefined (reading 'array') class Bar { array = new Array(); } class Foo { foo = this.bar.array; // Property &apo ...

Updating user data with Firebase cloud functions

For my e-commerce project, I am looking to utilize the Google Maps API to input the location of a user's shop. I have successfully utilized Google Cloud Functions to insert the latitude, longitude, and address data. Currently, the data can be insert ...

Evaluating file selection and uploading functionality within Spectron

Currently, I am faced with the challenge of writing a test for an electron GUI that includes a choose file dialog. Unfortunately, I do not have access to the inner workings of the GUI. Here is the code snippet I have written: await app.client.chooseFile( ...

Could JSON be the solution for combining a number and a string in a single key-value pair?

I am working on defining a nested JSON object that will store a key value pair with an integer (representing the amount of something) in use case 1, and a key value pair with a string (UUID) in use case 2. The ultimate goal is to analyze this data in futu ...

Troubleshooting TypeScript when importing external JavaScript: Module not found or no type declaration file available

I recently acquired a VueJS admin template built in JS and am looking to integrate it into my existing TS application. However, when I attempt to transfer the components, views, and other elements, I encounter the following error message. Is there a way to ...

Urgent dependency alert: calling for a necessity (sequelize) in next.js is a vital element

I'm encountering a challenge with integrating sequelize into my Next.js 13 project to connect my API routes with the database. I keep receiving errors that say "Critical dependency: the request of a dependency is an expression." import * as pg from &a ...

Could you lend a hand in figuring out the root cause of why this Express server is constantly serving up error

I am encountering a 404 error while running this test. I can't seem to identify the issue on my own and could really use another set of eyes to help me out. The test involves mocking a request to the Microsoft Graph API in order to remove a member fro ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...