skip to Main Content

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


  1. Chosen as BEST ANSWER

    Solved with the following:

    sleep = (ms: number) => new Promise<void>(r => setTimeout(r, ms));
    

  2. instead of

    sleep = (ms:number) => new Promise(r => setTimeout(() => r, ms));
    
    sleep = (ms) => new Promise(r => setTimeout(r, ms));
    // replace `() => r` with `r`
    

    So the problem is, inside setTimeout, instead of execute function r you currently return a function r and setTimeout not using it.

    setTimeout(() => r, ms)
    // same as
    setTimeout(() => {
      // you doing nothing here
      return r; // setTimeout not using this
    }, ms)
    

    Learn more at document of setTimeout at here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search