Why isn't my Promise fulfilling its purpose?

Having trouble with promises, I believe I grasp the concept but it's not functioning as expected in my project.

Here is a snippet of my code :

(I am working with TypeScript using Angular 2 and Ionic 2)

ngOnInit() {
  Promise.resolve(this.loadStatut()).then(() => this.testStatut());
}

testStatut() {
  if (this.admin !== undefined) {
    this.navCtrl.push(ConnectPage);
  } else {
    console.log("Undefined")
  }
}

admin;
loadStatut() {
  this.storage.get('admin').then((val) => {
    this.admin = val;
    console.log(this.admin)
  });
}

testStatut sends a response before loadStatut, whereas I require the opposite order.

I experimented with other functions and they worked as expected :

ngOnInit() {
  Promise.resolve(this.test1()).then(() => this.test2());
}

test1() {
  console.log("1")
}

test2() {
  console.log("2")
}

In this example, test1 precedes test2 execution orderly.

Answer №1

Here's the modified code for you to try out:

ngOnInit() {
  this.loadStatus().then(() => this.checkStatus());
}

checkStatus() {
  if (this.admin !== undefined) {
    this.navCtrl.push(ConnectPage);
  } else {
    console.log("Admin status is Undefined")
  }
}

admin;
loadStatus() {
  return this.storage.get('admin').then((val) => {
    this.admin = val;
    console.log(this.admin)
  });
}

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

Converting input tag to a method in component with uppercase transformation

Currently, this code resides within the <input tag I am looking to convert this code into a method in my component. Any ideas on how to do this? oninput="let p=this.selectionStart; this.value=this.value.toUpperCase(); this.setSelectionRange(p,p) ...

Angular auto-suggestion using Observable

I'm encountering an issue with Angular's autocomplete feature, where I'm having trouble displaying names instead of IDs. You can see the problem in the screenshot here: https://i.sstatic.net/uqk79.png The data is retrieved as an Observable ...

I'm eager to showcase live, incoming data on the chart. However, I'm feeling a bit lost on how to proceed. Can you help

I am currently utilizing the line chart feature of ng2-charts in my Angular project. However, I am unsure how to create a graph with real-time data. Here is an example of some sample data being used for the line chart: lineChartData: ChartDataSets[] = [ { ...

Encountering the error "TS(2604): JSX element type 'App' does not have any construct or call signatures" while trying to export an array of JSX Elements

I have a function that returns an array of JSX Elements. When I pass this to ReactDOM.render, I encounter the error mentioned above. wrappers.tsx const FooterWithStore:React.FC = () => ( <Provider store={store}> <FooterLangWrapper ...

Dealing with useEffect being invoked twice within strictMode for processes that should only execute once

React's useEffect function is being called twice in strict mode, causing issues that need to be addressed. Specifically, how can we ensure that certain effects are only run once? This dilemma has arisen in a next.js environment, where it is essential ...

A solution to the error message "Type 'unknown' is not assignable to type 'Country[]' in React TypeScript" is to explicitly define the type of the

I encountered error TS2322: Type 'unknown' is not assignable to type 'Country[]' pages/Countries/index.tsx Full code: import * as ApiCountries from '../../services/APIs/countries.api' function Countries() { const findCo ...

Tips for successfully passing the dynamic state and setState to a function in typescript

I'm encountering an issue with passing dynamic state and setState into a function using Typescript. Despite trying to use Generics, I am facing complaints from Typescript. Here is the code snippet: const handleSelectTag = (tag: { color: string; labe ...

Setting up TypeScript in Jest without the need for webpack

Currently, I'm developing an NPM module using TypeScript without the use of Webpack for compiling scripts. I need some guidance on configuring Jest to properly run tests with TypeScript files. Any recommendations? // test.spec.ts import {calc} from ...

What causes the variation in Http Post Response between the Console and Network response tab?

Currently, I am tackling an issue in angular2 related to HTTP post response. The problem arises when my endpoint is expected to return a boolean value. Interestingly, the response appears correctly in Chrome's Network response tab; however, upon loggi ...

Encountered error in Angular unit testing: Route matching failed to find a match

I am currently working on unit testing in my Angular 15 application. While running the test, I encountered the following error: Error: Cannot match any routes. URL Segment: 'signin' Below is the code for the unit test of my component: fdescribe ...

Identifying modifications within the @Input property in Angular 4

Can someone clarify how to detect changes in an @Input property within a component, rather than just when passed from its parent? I haven't found a clear answer to this yet. Thank you! ...

The type 'string[]' is missing the required property 'label', resulting in a typescript error

Within my codebase, I've defined a type called Person that looks like this : type Person = { value?: string[]; label?: string[]; }; Additionally, there is a promise function in my project: async function main(): Promise<Person> { const fo ...

Unable to display Google Places place_id when submitting a form in Angular/Ionic

Currently, I'm utilizing Google places autocomplete to fetch an array of places in the Ion-Searchbar. The form submission works smoothly, except for the input of the autocomplete field, which ideally should be the place_id instead of the actual input ...

Unit testing of an expired JWT token fails due to the incorrect setting of the "options.expiresIn" parameter, as the payload already contains an "exp" property

I am having trouble generating an expired JWT token for testing purposes and need some guidance on how to approach it. How do you handle expiration times in unit tests? This is what I have attempted so far : it('should return a new token if expired& ...

What is the best method for sorting through observable data pulled from an API?

public data$: Observable<any[]>; ngOnInit(): void { this.data$ = this.InventoryService.getAllProducts(); } searchProducts(event: any) { let searchTerm: string = event.target.value; console.log(searchTerm); this.data$.pipe( ...

Looking to incorporate form data into a nested object within Firebase using Angular2 - how can I accomplish this?

Trying to include user data in my Angular Fire object. This is how the database structure appears: Attempting to incorporate data into the roles object using the following code: Admin <label> Dealer</label&g ...

Exploring a Component's props and their data types

As a newcomer to React and Typescript, I have a straightforward question that I can't seem to find an answer to. I'm attempting to construct a tab layout using Typescript with headless UI following the documentation here I am encountering issue ...

Utilizing a string as an argument in a function and dynamically assigning it as a key name in object.assign

Within my Angular 5 app written in TypeScript, I have a method in a service that requires two arguments: an event object and a string serving as the key for an object stored in the browser's web storage. This method is responsible for assigning a new ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

Utilizing Google Sheets as a secure, read-only database for Angular applications without the need to make the sheet accessible to the

Seeking a way to utilize Google Sheets document as a read-only database for my Angular application, I have attempted various methods. However, the challenge with all these approaches is that they necessitate public sharing of the Sheet (accessible to anyon ...