2

I'd like to get Object using Promise. Bellow, is the method:

async getUri()
  {
      var data = this.userService.getOrders();
      var outside_uri = await data.then((uri) => { console.log('inside => ' + uri); return uri;})
      console.log('outside => ' + outside_uri)
  }

where

getOrders(): Promise<Profession[]>
    {
        return this.http.get<Profession[]>(`${this.baseUrl}/users/professions/id/2`)
                        .toPromise()
                        .then((response) => response);
    }

But when I call this method on ngOnInit() like that:

console.log("-----Result: " + this.getUri());

It produces:

-----Result: [object Promise]

inside => [object Object]

outside => [object Object]

Have you please any idea about solving that ?. Big Thanks.

Jolia
  • 109
  • 1
  • 8
  • `this.getUri().then(uri => console.log('-----Result:' + uri))` or you need `await this.getUri()` – Alexander Staroselsky Jun 28 '19 at 15:30
  • Hello Sir @AlexanderStaroselsky, thanks for your reply I tried `console.log(this.getUri().then(uri => console.log('-----Result:' + uri)));`, but, I got `inside => [object Object] outside => [object Object] -----Result:undefined` – Jolia Jun 28 '19 at 15:33

2 Answers2

4

Your code has a tiny mistake in getOrders function since you're solving the promise within the body of the method , and the function expect you to get a promise

So edit your code to fit the following

getOrders(): Promise<any>
    {
        return this.http.get(`${this.baseUrl}/users/professions/id/2`)
                        .toPromise();
    }

And

async getUri()
  {
      let data = this.userService.getOrders();
      let outside_uri;
      await data.then((uri) => { 
           console.log('inside => ' + uri); 
           outside_uri = uri;
        })
      console.log('outside => ' + outside_uri)
  }
Abdulrahman Falyoun
  • 3,676
  • 3
  • 16
  • 43
0

You need to use await to wait for the promise to resolve.

You need to await this.userService.getOrders(); and this.getUri() in your console.log

So your console.log should look like:

var uri = await this.getUri()
console.log("-----Result: " + uri);
ViqMontana
  • 5,090
  • 3
  • 19
  • 54