1

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 ?

Bhuvaneshwaran
  • 192
  • 1
  • 2
  • 10
Kantine
  • 747
  • 6
  • 14
  • Typo: `() => r` the function you call when the timeout finishes **mentions** the resolve function but it doesn't **call** it. – Quentin May 22 '23 at 09:39

2 Answers2

1

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

Update:

  • fix: No overload matches this call
const sleep = (ms: number) => new Promise<void>((resolve) => {
    setTimeout(() => {
        resolve()
    }, ms);
});
nhy
  • 169
  • 1
  • 2
  • 7
  • With your suggestion I get the following error in VSCode: `No overload matches this call. Overload 1 of 4, '(handler: () => void, timeout: number): number', gave the following error. Argument of type '(value: unknown) => void' is not assignable to parameter of type '() => void'. Overload 2 of 4, '(handler: () => void, timeout: number): number', gave the following error. Argument of type '(value: unknown) => void' is not assignable to parameter of type '() => void'.ts(2769)` – Kantine May 22 '23 at 10:08
  • @Kantine I update the code, i make it a little bit longer version of it. – nhy May 22 '23 at 23:17
0

Solved with the following:

sleep = (ms: number) => new Promise<void>(r => setTimeout(r, ms));
Kantine
  • 747
  • 6
  • 14