I try to implement a sleep method for a React Native application in Typescript. My implementation is the following:
sleep = (ms:number) => new Promise(r => setTimeout(() => r, ms));
inspired by How to implement sleep function in TypeScript?
And I use it this way in a Component:
getData = async () => {
this.setState({isLoading: true});
await this.sleep(1000);
const res = await getUser("test") ?? new User("", "", "", null, null, 0, 0);
this.state.isLoading = false;
this.setState({user : res, isLoading: false});
}
But using break points, I noticed that the code doesn’t go further than await this.sleep(1000);
and my application stays in loading state. What could be the reason for this ?
2
Answers
Solved with the following:
instead of
So the problem is, inside
setTimeout
, instead of execute functionr
you currently return a functionr
andsetTimeout
not using it.Learn more at document of
setTimeout
at here