英文:
setTimeout never ends in typescript
问题
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 https://stackoverflow.com/questions/37764665/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?
英文:
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 https://stackoverflow.com/questions/37764665/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 ?
答案1
得分: 1
Here's the translated content:
替换成:
sleep = (ms) => new Promise(r => setTimeout(r, ms));
// 用 `r` 替代 `() => r`
问题在于,在 setTimeout
内部,你当前返回了一个函数 r
,而 setTimeout
没有使用它。
setTimeout(() => r, ms)
// 相当于
setTimeout(() => {
// 这里你什么都没做
return r; // setTimeout 没有使用这个
}, ms)
在这里查看 setTimeout
的文档以了解更多信息。
更新:
- 修复:
No overload matches this call
const sleep = (ms: number) => new Promise<void>((resolve) => {
setTimeout(() => {
resolve()
}, ms);
});
英文:
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);
});
答案2
得分: 0
Translated:
解决方法如下:
sleep = (ms: number) => new Promise<void>(r => setTimeout(r, ms));
英文:
Solved with the following:
sleep = (ms: number) => new Promise<void>(r => setTimeout(r, ms));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论