首页 > 解决方案 > 如何在 react-native 组件中运行 async await 并延迟?

问题描述

如何延迟 5 秒运行此功能?

export default class Splash extends React.PureComponent  {

constructor() {
    super();
    this._bootstrapAsync();
 }
bootstrapAsync = async () => {
    //await Task.Delay(5);
    //await timeout(5000)
    //await sleep(5000);
    const userToken = await AsyncStorage.getItem('userToken');
    this.props.navigation.navigate(userToken ? 'App' : 'Auth');
  };

我试过这些:

 await Task.Delay(3);

 await timeout(5000);

 await sleep(2000);

标签: javascriptreact-nativeasync-await

解决方案


这个承诺在ms几毫秒内解决:

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

您可以像使用它await sleep(5000)而不是对您不起作用的代码一样使用它。


推荐阅读