9

I keep trying to use tutorials but can't seem to figure out how to use Promises or async await.

I have an http GET request and I want to wait for the result from the API before returning. The coming back as null because the function returns before the GET occurs.

HTTP GET

get_UserAccess(practiceId: number, userId: number): UserAccess {
    var d: UserAccess;

    this.httpclient.get(this.URL).subscribe.(data => {
      d = data as UserAccess;
    });

    return d; //Keeps returning as null

Calling Component

var userAccess = this.dataService.get_UserAccess(this.practice.practiceId, this.users[i].userId);
this.loadAccess(userAccess);

I've tried adding the await and async tags to the get request, but I'm not sure how to work with the promise that it returns to the calling component..

Justiciar
  • 356
  • 1
  • 3
  • 20
  • 1
    @OnurArı this is not c#. thanks though! – Justiciar Aug 15 '19 at 14:38
  • Independent of the programming language the idea is the same. Your understanding of async calls is wrong that is why it can help. – Onur Arı Aug 15 '19 at 14:39
  • See the aforementioned [suggested duplicate](https://stackoverflow.com/q/14220321/1260204). Asynchronous calls are a common and critical building block in writing/designing an application. It is critical that you understand how to work with asynchronous calls in javascript, and by extension typescript. Understanding these core concepts will help you become a better programmer and also ensure you do not keep "stubbing your toe" on the same problem. – Igor Aug 15 '19 at 14:42

2 Answers2

14

You can use await operator like that:

async getAsyncData() {
    this.asyncResult = await this.httpclient.get(this.URL).toPromise();
    console.log(this.asyncResult);
}
StepUp
  • 36,391
  • 15
  • 88
  • 148
5

HTTP GET

get_UserAccess(practiceId: number, userId: number): UserAccess {
return this.httpclient.get(this.URL); //Keeps returning as null

Calling Component

async func(){
var userAccess =await this.dataService.get_UserAccess(this.practice.practiceId, 
          this.users[i].userId).ToPromise();
this.loadAccess(userAccess);
}

pay attention that every function that calls func() should be with async signature too. goodluck :)

tehila
  • 135
  • 7