在构造函数中调用具有await关键字的函数?

问题描述 投票:1回答:4
class AuthLoadingScreen extends React.Component {
  constructor(props) {
    super(props);
    this._bootstrapAsync();
  }

  // Fetch the token from storage then navigate to our appropriate place
  _bootstrapAsync = async () => {
    const userToken = await AsyncStorage.getItem('userToken');

    // This will switch to the App screen or Auth screen and this loading
    // screen will be unmounted and thrown away.
    this.props.navigation.navigate(userToken ? 'App' : 'Auth');
  };

  // Render any loading content that you like here
  render() {
    return (
      <View>
        <ActivityIndicator />
        <StatusBar barStyle="default" />
      </View>
    );
  }
}

我知道等待将等待执行,直到承诺结算。这里我们在构造函数中调用具有await关键字的bootstrapAsync函数,这是否意味着构造函数执行将等到promise解析?

javascript react-native react-navigation
4个回答
1
投票

你正在使用的是AuthLoader是一个利用SwitchStackNavigator的“开关加载器组件”。这是一个您希望尽可能少花时间的屏幕。

为什么?好吧,因为除了无限期的进度条之外没有任何内容要显示。这就是为什么在构造函数中调用bootstrap async的原因。

构造函数执行将等到promise结算?

不,它不会。切换加载程序的想法是加载应用程序的当前状态并重定向(也就是switch)到正确的路由。

这就是为什么屏幕是否安装无关紧要的原因,这就是为什么在构造函数中调用bootstrapAsync的原因,因为它是最早可以调用的。


0
投票

它不会等待,因为构造函数不是异步函数,并且在函数调用之前没有等待。

为了等到函数结束执行代码,您需要使用.then()


0
投票

不,不会。为了确保Promise解决,直到构造函数返回值,你应该实际从构造函数返回Promise并等待它。

class AuthLoadingScreen extends React.Component {
    // async can't be used with constructor, so we just return Promise
    constructor(props) {
        super(props);
        return new Promise(resolve => {
            _bootstrapAsync().then(() => resolve(this))
        })
    }

    // Fetch the token from storage then navigate to our appropriate place
    // async function returns Promise
    _bootstrapAsync = async () => {
       const userToken = await AsyncStorage.getItem('userToken');

       // This will switch to the App screen or Auth screen and this loading
       // screen will be unmounted and thrown away.
       this.props.navigation.navigate(userToken ? 'App' : 'Auth');
    };

    // Render any loading content that you like here
    render() {
        return (
            <View>
                <ActivityIndicator />
                <StatusBar barStyle="default" />
            </View>
        );
    }
}
// construct the object in async function
const instance = await new AuthLoadingScreen()

确保它在这里工作是一个示例:

(async () => {
    class foo {
        constructor() {
            console.log(2)
            return new Promise(resolve => resolve(this)).then(() => console.log(3))
        }
    }

    console.log(1)

    const b = await new foo()

    console.log(4)
})()

1 2 3 4是输出


-1
投票

我认为你应该将this._bootstrapAsync()方法从constructor移动到componentDidMount()生命周期方法。

此外,有许多方法可以授权用户。最佳做法是为私有路由创建路由组件。 Example

© www.soinside.com 2019 - 2024. All rights reserved.