Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading an async function in constructor or ngOnInit

I want to call a async function readUsers() within the constructor or ngOnInit(). Although I used a recommended workaraound from here it still is delayed and does not wait in execution.

async constructor functions in TypeScript?

How can I delay/wait with execution of my readUsers() function?

users: any[];

ngOnInit() {
    this.readUsers();
    //this.readUsers(); above is called delayed so this.users below is 
    //undefined
    console.log(this.users);
}


public readUsers = async () =>  {
    this.users = await this.userService.getUsers()
    .then(resolve=>{
        console.log("within async function");
        return resolve;
    })
    .catch(reject=>{
        return [];
    })
}


////////userService.getUsers() reads JSON Object from an endpoint (works!)
getUsers(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.http
            .get('https://url.com/users/')
            .subscribe(users => {
                if (!users) {
                    reject([]);
                }
                resolve(users);
            });
    });
}

The console.log is switched as there is no waiting:

undefined

within async function

like image 455
SantaTheManiac Avatar asked Jan 19 '19 23:01

SantaTheManiac


People also ask

Can I use async on ngOnInit?

According to this comment in issue 17420: "it's not a problem for someone to use async ngOnInit , it is just an awkward/not recommended coding practice."

Can we use async in constructor?

A simple answer for that: No, we can't! Currently, class constructors do not return types, and an asynchronous method should return a Task type.

How do you call async method in constructor typescript?

async function run() { let topic; debug("new TopicsModel"); try { topic = new TopicsModel(); } catch (err) { debug("err", err); } await topic. setup(); constructor. typescript.


1 Answers

interface OnInit {
  ngOnInit(): void
}

When something returns a void, then you can generally convert it to a Promise without any side-effects

async ngOnInit(): Promise<void> {
    await this.readUsers();
    console.log(this.users);
}
like image 102
Pavlo Avatar answered Oct 04 '22 23:10

Pavlo