javascript - 在函数内部调用函数,只有在函数结束后才会发生其余代码
问题描述
我想先调用 getUser() 函数(首先检查是否有用户登录),然后才调用其余的函数代码。
我有一些类似的功能,需要用户登录才能发生,而不是复制代码,我想每次都调用 getUser() 函数。
我需要解释的函数的顺序:
addComment = () => {
this.getUser() // check if user is logged with getItem and setState userOnline boolean
/// only after the getUser is done will continue with this code -
if (this.state.userOnline == true)
{
/// fetch and other function code
this.setState({userOnline : false});
}
else {
Alert.alert("You have to be logged-in to publish comments");
return;
}
}
获取用户功能 -
async getUser() {
try {
const user = await AsyncStorage.getItem("@Ye-Music:user");
if (user !== null) {
this.setState({ userData: JSON.parse(user) });
this.setState({ userOnline: true})
}
} catch (error) {}
}
解决方案
如果你是异步的,你需要使你的addComment
函数异步getUser()
,它是,考虑到它正在做setState()
。然后你需要await getUser()
在执行其余代码之前。
addComment = async () => {
await getUser();
//... rest of the code
}
推荐阅读
- string - 存储非整数与其表示为字符串之间的区别
- python - Github3.py 1.3.0 获取提交时间戳
- java - 单行中的多个后缀和前缀操作
- ios - iOS - 在前台接收 FCM 推送消息
- python - 仅在所有构建成功后才部署
- html - 所有页面上的 CSS @page background-images?
- .net - 如何使用 ASP.NET MVC 将数组作为参数传递到 SQL Server
- javascript - 如何替换 HTML 元素的 data 属性中的值
- python - python3 manage.py runserver 命令没有响应
- php - 无论如何要处理授权令牌不匹配错误