The Promise.then() function is not patient

Whenever I attempt to use Promise.then(), the events from this.events, this.tmEvents, and this.totalEvents keep logging before the promises are fully complete. Even when I tried implementing async/await to prevent this, I faced the same issue. Is there a way to delay these functions until the promises are resolved? Interestingly, if I log this.tmEvents in the getEvents function, it always shows up after those 3 events.

//this.data.tmevents (Dataservice)
  public tmEventsSource = new BehaviorSubject<any>([]);
  tmEvents = this.tmEventsSource.asObservable();
  newTmevents(tmEvents) {
    this.tmEventsSource.next(tmEvents);
  }


  async fetchEvents() {
    await this.getEvents();
    await this.getTmEvents();
    this.data.tmEvents.subscribe(tmEvents => {
        this.totalEvents = this.totalEvents.concat(this.events);
        this.totalEvents = this.totalEvents.concat(tmEvents);
        console.log(this.events);
        console.log(tmEvents);
        console.log(this.totalEvents);
        this.shuffle(this.totalEvents);
    });

  async getTmEvents() {
    const storedTMEvents = JSON.parse(localStorage.getItem(this.TM_EVENTS));
    if (storedTMEvents == null) {
        try {
            const res = await this.getUserLocationServ();
            await this.getTmEventsServ(res);
        } catch(err) {
            console.log(err);
        }
    } else {
        this.data.newTmevents(storedTMEvents);
    }
}

Answer №1

In order to create a chain, you must return them and consider using async / await to simplify the process.

Here is an example that waits for everything and improves readability:

async fetchEvents() {
    await this.getEvents();
    await this.getTmEvents();
    this.data.tmEvents.subscribe(tmEvents => {
        this.tmEvents = tmEvents;
        this.totalEvents = this.totalEvents.concat(this.events);
        this.totalEvents = this.totalEvents.concat(this.tmEvents);
        console.log(this.events);
        console.log(this.tmEvents);
        console.log(this.totalEvents);
        this.shuffle(this.totalEvents);
    });
}

async getTmEvents() {
    const storedTMEvents = JSON.parse(localStorage.getItem(this.TM_EVENTS));
    if (storedTMEvents == null) {
        try {
            const res = await this.getUserLocationServ();
            await this.getTmEventsServ(res);
        } catch(err) {
            console.log(err);
        }
    } else {
        this.data.newTmevents(storedTMEvents);
    }
}

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

iOS 10.3.1 causing Ionic 2 (click) event to trigger twice

I am currently working on an Ionic 2 app and I am facing an issue with the click event. When I test the app on a device and click on a button, let's say to trigger an alert, the function executes once. However, if I click on the button again, the fun ...

Alias for function in TypeScript declaration file (.d.ts)

There is a function within a Node module that I am trying to document in a .d.ts file. This function has two aliases, config() and load() (check the source here). The function definition in the dotenv/index.d.ts file looks like this: export function confi ...

Is there a way to retrieve the index and specific object that was modified using $watch in Angular?

I am receiving an array of objects from an API that is being updated every 2 seconds. I have a $watch function that is monitoring any changes in this array. I want to be able to identify which elements have changed along with their index, so that I can dyn ...

What is the best way to send parameters to an async validator when working with reactive controls in Angular

Issue with Validation I am facing a challenge while using the same component for both read and edit routines. The async-validator functions perfectly when dealing with new entries. However, a problem arises if the user mistakenly changes a value and then ...

Angular is having trouble progressing after a stylesheet has been chosen

$ ng new my-app ? Do you want to include Angular routing in your project? Yes ? Which stylesheet format do you prefer to use? CSS Unfortunately, the next steps are not proceeding as expected. The process seems to be stuck and even keyboard shortcuts like ...

Using Angular 2 with the firebase-admin sdk

Whenever I attempt to integrate the firebase-admin SDK into my Angular2 project, an error occurs: ERROR in ./~/firebase-admin/lib/auth/token-generator.js Module not found: Error: Can't resolve 'jsonwebtoken' in '/home/koucky/git_projec ...

How to create a karma-jasmine test case in Angular 2 to trigger a modal opening when a link is clicked

I need to verify that when a link is clicked, a modal should open. In my spec.ts file, I have written the following test: describe('NavbarComponent', () => { let comp: NavbarComponent; let fixture: ComponentFixture<NavbarComponent& ...

Angular reactive forms - validate on both change and blur events with real-time feedback

In my application, I am utilizing angular reactive forms to handle validations. The specific requirement I have is that certain validations should be triggered on change, which is the default behavior of angular form validation, while others should only oc ...

Guide for using two Async Pipe functions in Angular 7

Two different functions are in place to check a specific condition, and the requirement is for both of them to be true simultaneously. How can *ngIf be utilized to achieve this? Currently, setting just one of them works, but the aim is to have both. HTML ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

"Combining the power of AngularJS2 beta with Spring Boot: the ultimate

I am currently using Atom 1.4.0 with the atom-typescript package to develop AngularJS2 modules in TypeScript. On the backend, I have a spring-boot application for handling the REST APIs. After making changes to the .ts files in Atom, it seems to compile t ...

Transfer configuration information to a dependency of an Angular library by utilizing the "forRoot" method

I've developed two Angular libraries - one that depends on the other. The dependent library requires configuration through the forRoot method. How can I effectively pass the configuration data from the parent library to its dependency? For instance, ...

Discover how TypeScript enhances JavaScript by defining Built-In Types during the compilation process

When I first delved into the world of scripting languages, JavaScript felt manageable. However, things got confusing when I shifted my focus to Angular2 with TypeScript. I soon discovered that TypeScript has the ability to define Built-In Types like strin ...

The type 'NextApiRequest' lacks the following attributes compared to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'

An error has been identified in the code for a Next.js project below. The error message reads: Argument of type 'NextApiRequest' is not assignable to parameter of type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any ...

When it comes to utilizing BehaviorSubject.value and AsyncSubject in RXJS, it is essential to understand

As a newcomer to RXJS, I am seeking advice on whether my current approach is considered best practice. My situation involves an API that returns a list of countries which needs to be utilized across multiple components. The external API can sometimes be sl ...

Creating a new object in a Redux selector and returning it can be achieved by following these steps

Is there a way to create a new object in Redux selector and return it? I've been searching online, but haven't found an answer. For example: export interface UserModel { user: string, job: string, contact: string, sex: string // ...

Developing specialized error messages embedded within backend feedback using Angular

In my Angular8 application, the server consistently provides responses in the 200s series. Any errors from the server are encapsulated within the Response object, which means I have to generate errors from it. A standard response looks like this: The APP_ ...

The Angular2 component link imported in the core.module is not functioning properly

Adhering to the guidelines provided in the Angular style guide found at https://angular.io/styleguide#!#04-11, I have created a simple navigation setup. My app.component contains links like <a routerLink="hello">hello</a>, which work perfectly ...

Ways to bounce back from mistakes in Angular

As I prepare my Angular 5 application for production, one issue that has caught my attention is how poorly Angular handles zoned errors. Despite enabling 'production mode', it appears that Angular struggles to properly recover from these errors. ...

Attempting to establish a connection with Redis through the combination of TypeScript and Node.js

Currently, I am attempting to establish a connection with Redis using TypeScript and Node.js. However, I am encountering an issue where **error TS2693: 'RedisStore' is designated as a type but is being utilized as a value in this context.** let r ...