Home > Software engineering >  How can i wait for my call without using async on my ngOnInit method?
How can i wait for my call without using async on my ngOnInit method?

Time:12-17

I have the following code. To wait for my async call I am using the following

 testi() {
   return new Promise((resolve,reject) => {
     resolve(true);
   })
  }


  async ngOnInit() {
    let pp = await this.testi();
    console.log('pp', pp);

}

is there any other way with which I can wait for the call here without adding async notation on my ngOnInit method?

CodePudding user response:

You can use then instead of await:

testi() {
  return new Promise((resolve,reject) => {
    resolve(true);
  });
}

ngOnInit() {
  this.testi()
    .then(value => console.log(`pp: ${value}`))
}

If you are writing Typescript code, chances are that your compiled code will uses then instead of await. It is the "old" way of using promises.

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

If you create a Promise inside then, you can return it to chain calls to then and avoid the pyramid of doom:

ngOnInit() {
  this.testi()
    .then(value => new Promise((resolve, reject) => resolve(`Hello ${value}`)))
    .then(value => new Promise((resolve, reject) => resolve(`${value}!`)))
    .then(value => console.log(value));
}

CodePudding user response:

You can subscribe to it..

 ngOnInit() {
    this.testi().subscribe((pp:any) => {
       console.log('pp', pp);
    }
}

  • Related