首页 > 解决方案 > 在函数内部调用函数,只有在函数结束后才会发生其余代码

问题描述

我想先调用 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) {}
  }

标签: javascriptreactjsfunctionreact-nativeasynchronous

解决方案


如果你是异步的,你需要使你的addComment函数异步getUser(),它是,考虑到它正在做setState()。然后你需要await getUser()在执行其余代码之前。

addComment = async () => {
    await getUser();
    //... rest of the code

}

推荐阅读