Angular Promise.all not functioning as expected within a timeout event

Encountering an Angular 6 issue that involves waiting for promises to be resolved before proceeding. The code below successfully demonstrates this functionality:

AppService.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AppService {

  p1: Promise<any>;
  p2: Promise<any>;

  constructor() { 
    this.getPromise1();
    this.getPromise2();
  }

  getPromise1() {
    this.p1 = new Promise((resolve, reject) => {
      resolve(true);
    });
  }

  getPromise2() {
    this.p2 = new Promise((resolve, reject) => {
      setTimeout(() => resolve(true), 5000);
    });
  }
}

AppComponent.ts

import { Component, AfterViewInit } from '@angular/core';
import { AppService } from './app.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  implements AfterViewInit {

  constructor(private appSrvc: AppService) { }

  ngAfterViewInit(){
    Promise.all([this.appSrvc.p1, this.appSrvc.p2])
      .then(values => { 
          console.log(values);
          //Execute additional logic if all promises are resolved
      })
      .catch(error => { 
          console.log(error.message)
      });
  }
}

However, when attempting to make a similar setup using a timeout event in the initialize method of AppService.ts as shown below, the promises fail to work:

AppService.ts

 constructor() { 
    this.initialize();
  }

  initialize(){
    setTimeout(() => {
      this.getPromise1();
      this.getPromise2();
    }, 1000);
  }
  ...

The above implementation does not behave as expected, and I am seeking assistance in understanding why. Any help would be greatly appreciated.

Thank you!

Answer №1

Upon injection into the module, the AppService constructor is immediately called.

  1. A few milliseconds later, the AppComponent is injected.
  2. Approximately 100ms after that, the
    AppComponent=>ngAfterViewInit()
    function is executed.

If you set a timeout, delaying the initialization of promises by 1000ms, by that time the

AppComponent=>ngAfterViewInit()
has already finished and the values of the upcoming promises become undefined. To resolve this issue, synchronizing these two events is vital. Therefore, calling AppService.initialize() from AppComponent with an async mechanism will solve the problem.

Below is an example demonstrating how to synchronize these actions:

getPromise1() {
    if(!this.p1) {
        return this.p1 = new Promise((resolve, reject) => {
            resolve(true);
        });
    }
    return this.p1;
}
getPromise2() {
    if(!this.p2) {
        return this.p2 = new Promise((resolve, reject) => {
          setTimeout(() => resolve(true), 5000);
        });
    }
    return this.p2;
}

Then, at the call site:

ngAfterViewInit(){
    Promise.all([this.appSrvc.getPromise1(), this.appSrvc.getPromise2()])
        .then(values => { 
                console.log(values);
                //Execute some code when all promises have resolved
        })
        .catch(error => { 
                console.log(error.message)
        });
}

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

Is there a way to activate the autoplay feature for this?

I'm really new to Jquery and most of this code isn't mine, I'm just using it as a learning tool for creating sliders. If someone could give me some guidance on how to make this slider work automatically when the page loads, that would be gre ...

Enhancing Bootstrap 5 with JavaScript

I am relatively new to creating webpages and have recently started working on one using Bootstrap 5. I am looking to dynamically add or remove the "bg-opacity" Bootstrap class from my navbar based on the viewport width. I initially attempted to achieve thi ...

Issue encountered when using FormData to upload a file in Angular 6

I've been working on creating a file uploading system using Angular 6 for the front end and Lumen for the back end API. Strangely, while I can successfully upload files using Postman directly to the API, I'm facing issues when trying to do the sa ...

Encountered an issue: Unable to access property - fetch from firestore due to TypeError

While working on validating data from Firestore using *ngIf, I encountered an issue where only a few users had the property head = true in firestore. My goal is to ensure that every user has this property set to true. However, some users do not have head = ...

Troubleshooting: Why Isn't Calling a PHP Function from AJAX Working

I'm attempting to utilize AJAX to call a PHP function. Here's the script I've implemented. <script type="text/javascript" src="jquery.1.4.2.js"> $(document).ready(function () { // after EDIT according to ...

What could be the reason for the malfunction of the Bootstrap panel toggle feature in a ReactJS production build

In my ReactJS development, I have successfully added Bootstrap panel toggle functionality. However, I encountered an issue when deploying the React build code - the panel is not expanding. After investigating, I realized that the problem lies in using hr ...

"Exploring the process of implementing a fixed method POST in Angular 5

When developing an application for Portal, I encountered an issue where a newly created role is not displayed without refreshing the browser. How can I ensure that the added element is directly displayed in the table without needing to refresh the browser? ...

The sinuous waveform in JavaScript

track : function(x, y, top, ampl) { return { top : top + 2, x : x + ampl * Math.sin(top / 20), y : (top / this.screenHeight < 0.65) ? y + 2 : 1 + y + ampl * Math.cos(top / 25) }; } This specif ...

Are you looking to enhance your website with dynamic and

I am looking to display dynamic text in a label using HTML. This label should be populated with text from a Javascript function upon loading or reloading the page. How can I make this happen? <label id="MyLabel"></label> <script type="tex ...

Extending an interface in Typescript using a generic interface

Suppose I have the following interface: interface IAddress { addressProperty: any; } Is it possible to create an interface that resembles this one: interface ILoadable<T> { loading: boolean; } This way, I would be able to use it like so: ...

Is there a specific function that is triggered upon the successful completion of a subscription process?

I am facing an issue with the code below. The navigation is happening when a customer is created, instead of waiting for the address to be created successfully. Any assistance on this matter would be greatly appreciated. createCustomer(model: any) { ...

Switch the website title as soon as the user looks away from the tab

How can I capture the user's attention and bring them back to my website when they are on a different tab? I really like the effect used on sephora.pl where an alert pops up with the message 'What are you waiting for?' when you switch tabs. ...

React class cannot be exported at this time

Here is the content of two files: Product.jsx: class Product extends React.Component{ render(){ return ( <div className='item'> <div className='image'> <img src ...

Unable to retrieve selected value from Flowbite-React Datepicker due to malfunctioning props change event

I am encountering an issue with extracting the selected value from the Datepicker component in the flowbite-react library while using it with NextJS. The component is being displayed correctly. I attempted the code below, but it does not return anyth ...

UnknownReferenceError: jwreload has not been declared (Exploring dynamic routing in next.js)

Error in dynamic route with next.js Recently, I started learning next.js and encountered an issue while implementing a dynamic route. The error message "ReferenceError: jwreload is not defined" keeps appearing whenever I reload the page. Surprisingly, des ...

Utilizing a dropdown list from one HTML page on a separate HTML page

My web project includes a main html5 page called main.html and two additional html5 pages named country.html and state.html. The country.html page contains a select dropdown list with 250 countries listed as options. <select> <option value="1 ...

Exploring the integration of JSON data with Angular and Node.js

Hey everyone, I'm diving into the world of Node JS and Angular for the first time. Right now, I'm tackling the task of handling JSON files with Angular and Node JS, but I've hit a bit of a roadblock. My goal is to retrieve all elements (both ...

What is the best way to apply a class to a jQuery element only if a specific condition is met, and then remove it if the condition is no longer

Is there a more concise method to accomplish the same task? const selectAllCheckbox = $("input.select_all"); const isChecked = selectAllCheckbox.prop("checked"); isChecked ? selectAllCheckbox.parent().addClass("selected") : selectAllCheckbox.parent().r ...

stop tabs from being visible during window reload

I am currently working on a page that features 4 jQuery UI tabs. The first tab simply displays a greeting message saying "HELLO". The 2nd, 3rd, and 4th tabs contain HTML and PHP scripts that are functioning correctly. However, when I execute the PHP script ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...