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..
async and awaitInside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
Conversely, in Promise. all the two await calls can be started before either one is resolved.
How To Create Promises in Angular? To create a promise in Angular we just need to use 'new Promise(function)' syntax. The promise constructor takes function as a parameter and that inner function takes resolve and reject as a params.
You can use await
operator like that:
async getAsyncData() {
this.asyncResult = await this.httpclient.get(this.URL).toPromise();
console.log(this.asyncResult);
}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With