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
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."
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.
async function run() { let topic; debug("new TopicsModel"); try { topic = new TopicsModel(); } catch (err) { debug("err", err); } await topic. setup(); constructor. typescript.
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);
}
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