如何从诺言(异步/等待)中获取数据并使用``外部''诺言?
因此,我正在等待承诺实现,然后我想使用.then()
或async
函数的结果数据外部。
function HomeScreen() {
const userData = async () => {
await AsyncStorage.getItem("user_nicename")
}
return (
<View style={styles.container}>
<Text>Hello, { userData() } </Text> //*I want to use it here for example*//
<Button
style={styles.buttonLogin}
onPress={() => navigation.navigate('LoginScreen')}
title='Logout'
/>
</View>
)
}
export default HomeScreen;
当然,我的代码会引发错误,因为userData()
是“ Promise对象”。我只想要字符串值,在 内访问的字符串值。然后(数据=&gt; ...)
。但是如何在外面访问它,以便可以在其他地方使用它?
So I await for the promise to fulfil, then I want to use the resulting data outside of .then()
or the async
function.
function HomeScreen() {
const userData = async () => {
await AsyncStorage.getItem("user_nicename")
}
return (
<View style={styles.container}>
<Text>Hello, { userData() } </Text> //*I want to use it here for example*//
<Button
style={styles.buttonLogin}
onPress={() => navigation.navigate('LoginScreen')}
title='Logout'
/>
</View>
)
}
export default HomeScreen;
of course my code will throw an error because userData()
is a 'promise object'. I just want the string value, which I have no problems accessing inside .then(data => ... )
. But how do I access it outside so I can use it somewhere else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要使用
USESTATE
和使用effeft
You to use
useState
anduseEffect