Use promise with async

Viewed 110

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.

2 Answers

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)
  }

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);
Related