Angular 8 - How to use Promises and Async/Await [duplicate]
Asked Answered
E

2

10

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..

Era answered 15/8, 2019 at 14:34 Comment(3)
@OnurArı this is not c#. thanks though!Era
Independent of the programming language the idea is the same. Your understanding of async calls is wrong that is why it can help.Counteract
See the aforementioned suggested duplicate. 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.Gristmill
R
16

You can use await operator like that:

async getAsyncData() {
    this.asyncResult = await this.httpclient.get(this.URL).toPromise();
    console.log(this.asyncResult);
}
Roderich answered 15/8, 2019 at 15:9 Comment(0)
P
6

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

Panayiotis answered 15/8, 2019 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.