The code inside the promise .then block is executing long before the promise has completed its

After spending quite some time working on this messy code, I finally have a functioning solution:

loadAvailabilities() {

    let promises = [];
    let promises2 = [];
    let indexi = 0;
    //return new Promise((resolve, reject) => {
      this.appointments = this.af.list('/appointments', { query: {
        orderByChild: 'selected',
        limitToFirst: 10
      }});
      let mapped;
      this.subscription2 = this.appointments.subscribe(items => items.forEach(item => {
        //promises.push(new Promise((resolve, reject) => {
          console.log(item);
          let userName = item.$key;
          //this.availabilities = [];
          for(let x in item) {
            let month = x;
            console.log(x + "      month");

            this.appointmentsMonth = this.af.list('/appointments/' + userName + '/' + month);
            this.subscription3 = this.appointmentsMonth.subscribe(items => items.forEach(item => {
                this.startAtKeyAvail = item.$key;
                //console.log(JSON.stringify(item) + "           item");
                let date = new Date(item.date.day * 1000);
                let today = new Date();
                console.log(date.getMonth() + "==" + today.getMonth()  + "&&" + date.getDate() + "==" + today.getDate());
                console.log("IN LOAD AVAILABILITIES *(*((**(*(*(*(*(*(*(*&^^^^%^%556565656565");
                if(date.getMonth() == today.getMonth() && date.getDate() == today.getDate()) {
                  console.log("            inside the if that checks if its today");
                  console.log(item.reserved.appointment + "                *************appointment");
                  //let counter = 0;
                  //mapped = item.reserved.appointment.map((r) => {
                  //item.reserved.appointment.forEach((r, index) => {
                    for(let r of item.reserved.appointment) {
                      promises.push(new Promise((resolve, reject) => {
                        if(r.selected == true) {
                          //this.renderer.setElementStyle(this.noavail.nativeElement, 'display', 'none');

                          let storageRef = firebase.storage().ref().child('/settings/' + userName + '/profilepicture.png');

                          let obj = {'pic':"", 'salon': userName, 'time': r.time};

                          storageRef.getDownloadURL().then(url => {
                            console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
                            obj.pic = url;
                            this.availabilities.push(obj);
                            console.log(JSON.stringify(this.availabilities));
                            resolve();
                          }).catch((e) => {
                            console.log("in caught url !!!!!!!$$$$$$$!!");
                            obj.pic = 'assets/blankprof.png';
                            this.availabilities.push(obj);
                            console.log(JSON.stringify(this.availabilities));
                            resolve();
                          });
                        }
                      }))

                  }

                }

               }))
             }
          }))
            //}));

          Promise.all(promises).then(() => {
            console.log("in load availabilities ......... ")
            console.log(JSON.stringify(this.availabilities));

            this.availabilities.sort(function(a,b) {
              return Date.parse('01/01/2013 '+a.time) - Date.parse('01/01/2013 '+b.time);
            });

            console.log('*****previous******');
            console.log(JSON.stringify(this.availabilities));
            console.log('*****sorted********');

            for(let i of this.availabilities) {
              console.log(i.time + "          this is itime");
              let date = new Date('01/01/2013 ' + i.time);
              console.log(date + "          this is date in idate");
              let str = date.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
              console.log(str);
              i.time = str;
            }
          });
      //}))



    //})

  }

The logs indicate that the storageRef.getDownloadURL() function occurs towards the end of page loading. This is where the objects are added to this.availabilities, which is later used to populate a list. The issue I faced was that the code within the Promise.all .then() block executed before any data was pushed to this.availabilities, resulting in an empty array upon sorting.

Answer â„–1

Implementing promises within individual forEach loops was the approach I took. By adding each promise to a unified collection and executing

Promise.all(collection).then(...)
as indicated, the asynchronous nature of operations led to a successfully sorted array.

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

Error TS2394: Function implementation does not match overload signature in Typescript

Take a look at this code that seems to be causing headaches for the TypeScript compiler: use(path: PathParams, ...handlers: RequestHandler[]): this use(path: PathParams, ...handlers: RequestHandlerParams[]): this use(...handlers: RequestHandler[]): this u ...

Is there a way to integrate TypeScript into the CDN version of Vue?

For specific areas of my project, I am utilizing the Vue CDN. I would like to incorporate Typescript support for these sections as well. However, our technical stack limitations prevent us from using Vue CLI. Is there a method to import Vue.js into a bas ...

Obtaining a return value from a function in Angular

After just starting to work with Angular, I am attempting to extract a value from a button displayed in the HTML using a function. `<button class="btn" id="btn-gold" (click)="value(9)" name="mybutton" value="9">` 9 I have also inclu ...

Different ways to pass a component function's return value to a service in Angular

On my HTML page, I am presenting job details within Bootstrap panels sourced from a JSON array using an ngFor loop. Each panel showcases specific job information along with a unique job ID. The panel is equipped with a click event which triggers the execut ...

Error: Failed to retrieve the name property of an undefined value within the Array.forEach method

Upon pressing the button to display the task pane, I encountered an error message in the console window that reads: "Uncaught (in promise) TypeError: Cannot read property 'name' of undefined". This error persists and I am unable to resolve or com ...

Differences between Typescript, Tsc, and Ntypescript

It all began when the command tsc --init refused to work... I'm curious, what sets apart these three commands: npm install -g typescript npm install -g tsc npm install -g ntsc Initially, I assumed "tsc" was just an abbreviation for typescript, but ...

When using the makeStyles hook in a function component with React, Material-UI, and Typescript, an Invalid Hook Call error may

I'm feeling lost and frustrated with my current coding issue. Despite following the guidelines in the (javascript) documentation, I keep encountering the dreaded Invalid Hook Call error. My setup includes TypeScript 4.1.2, React 17.0.1, and React Typ ...

Retrieving weather data in JSON format from the Open Weather Map API

Recently, I've been delving into learning Angular for my own personal growth. To aid in this journey, I've been diligently following tutorials on CodeAcademy and PluralSight, specifically focusing on the AngularJS: Get Started stream. While enco ...

Changing a method within a class does not automatically update how it is used in other classes that inherit from it

I am attempting to modify the alpha method in the context of the Cat class, and have the beta method reflect those modifications. const wrapperFn = <T extends (...args: any) => any> (a: T) => { return (...args: Parameters<T>) => ...

Prisma designs a personalized function within the schema

In my mongo collection, there is a field named amount. My requirement is to have the amount automatically divided by 100 whenever it is requested. In Django, this can be achieved with a custom function within the model. Here's how I implemented it: cl ...

Creating a dynamic method to set data for a stacked bar chart in chart.js

In the following code snippet, you can see how my stacked bar chart is rendered using Angular: <canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]=" ...

There is only a singular font awesome icon that appears properly based on the conditions set by [ngClass

I'm currently developing a user profile feature that allows users to submit links to their social media accounts. Each account is represented by a clickable icon, and the selection of which icon to display is based on various conditions within [ngClas ...

What is the best way to assign individual instance variable names in bulk while looping through and parsing an array of hashes?

Starting with a refined big hash that includes various details about a company. angel_hash = {"follower_count"=>1369, "name"=>"AngelList", "markets"=> [{"display_name"=>"Startups", "name"=>"startups", "id"=>448, "tag_type"=>"MarketTag ...

What are some key indicators in the source code that differentiate TypeScript from JavaScript?

Reviewing some code on Github, I am looking for ways to quickly determine whether the script is written in JavaScript or TypeScript. Are there any simple tips or hints that can help with this? For instance, when examining an array declaration like the on ...

The attribute 'selectionStart' is not a valid property for the type 'EventTarget'

I'm currently utilizing the selectionStart and selectionEnd properties to determine the beginning and ending points of a text selection. Check out the code here: https://codesandbox.io/s/busy-gareth-mr04o Nevertheless, I am facing difficulties in id ...

What is the best way to manually trigger a function($event) in Angular 2?

When working with Angular2, I recently wrote a function that utilizes $event. It works perfectly fine when triggered by a click event from the template class. However, I encountered an issue when trying to manually call this function and pass an event valu ...

Encountering a Node V18 Peer Dependency Conflicté”™

Can someone please help me understand what's causing this error? Every time I try to install a dependency, this keeps popping up. I'm completely lost and unsure of what's happening. npm ERR! 1 more (the root project) npm ERR! peer ...

npm ERROR! The requested resource at http://registry.npmjs.org/amcharts4 could not be located - Error 404: Resource Not Found

I'm running into an issue while trying to include npm package dependencies in my Angular project. Can anyone assist me in resolving this error? C:\Users\TM161\Desktop\Master\stage PFE\SNRT-Music>npm i npm ERR! code ...

Issue encountered while generating a fresh migration in TypeORM with NestJs utilizing Typescript

I am currently working on a Node application using TypeScript and I am attempting to create a new migration following the instructions provided by TypeORM. Initially, I installed the CLI, configured my connection options as outlined here. However, when I ...

Encountering issues with Next.js routing - Pages failing to load as expected

Having some trouble with the routing in my Next.js application. I've created a page named about.tsx within the "pages" directory, but when trying to access it via its URL (localhost:3000/about), the page fails to load correctly and displays: This Pa ...