Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 651
Justiciar Avatar asked Aug 15 '19 14:08

Justiciar


People also ask

Can we use promise and async-await together?

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.

Are promises and async-await same?

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.

Can you have two await on a promise?

Conversely, in Promise. all the two await calls can be started before either one is resolved.

How do you use promises in angular 8?

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.


2 Answers

You can use await operator like that:

async getAsyncData() {
    this.asyncResult = await this.httpclient.get(this.URL).toPromise();
    console.log(this.asyncResult);
}
like image 114
StepUp Avatar answered Nov 02 '22 12:11

StepUp


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

like image 23
tehila Avatar answered Nov 02 '22 12:11

tehila