javascript - 在构造函数中调用具有 await 关键字的函数?
问题描述
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 将等待执行,直到承诺解决。在这里,我们在构造函数中调用具有 await 关键字的 bootstrapAsync 函数,这是否意味着构造函数执行将等到 promise 解决?
解决方案
您使用的是react-nagivation,它是一个使用SwitchStackNavigatorAuthLoader
的“切换加载器组件” 。这是一个您希望在其中花费尽可能少的时间的屏幕。
为什么?好吧,因为除了无限的进度条之外没有要显示的内容。这就是在构造函数中调用 bootstrap async 的原因。
构造函数执行将等到承诺解决?
不,不会的。切换加载器的想法是加载应用程序的当前状态并将(又名switch
)重定向到正确的路线。
这就是为什么屏幕是否挂载都没有关系的原因,这就是为什么在构造函数中调用 bootstrapAsync 的原因,因为这是最早可以调用它的原因。
推荐阅读
- wifimanager - ESP8266 WiFiManager + 无法访问网页
- xamarin - 如何在 VS 2019 中向我的 Xamarin 项目添加系统命名空间?
- c# - 如何在 .NET 标准库中设置 IActionResult?
- reactjs - 有没有更好的方法来有条件地在 FE 上呈现这些 BE 响应?使用反应
- jenkins - 全局变量不能在 Jenkinsfile 的函数内使用
- c++ - 类链表类的析构函数的双重释放错误
- c# - Visual Studio 安装项目 .NET5 运行时下载失败
- android-studio - 如何在默认操作系统驱动器以外的驱动器上完全安装 Windows 10 上的 Android Studio?
- python - 关于python中的链表
- python - Jupyter notebook 不会运行带有模糊模糊功能的模糊匹配单元