如何在react-native中调用async fucntion

时间:2016-11-11 21:20:32

标签: javascript reactjs react-native

我只是试图调用异步函数,当我得到返回时,我想显示另一个视图。

这是我的索引:

const UserService = require('JitApp/services/UserService.js');
class App extends Component {

  state = {
      isLoad: false
  }

  getUser = async function() {
    UserService.getUser().then( function(user) {
      let isLogged;
      if(user){
        isLogged = true;
      }else{
        isLogged = false;
      }
      this.setState({'isLogged': isLogged});
      this.setState({'isLoad': true});
    }
    .catch(function(error) {
    console.log('There has been a problem with your fetch operation: ' + error.message);
    // ADD THIS THROW error
      throw error;
})
    );
  }.bind(this);

  render() {
    this.getUser();
    if(!this.state.isLoad){
        return(
          <ActivityIndicator
                animating={this.state.animating}
                style={[styles.centering, {height: 80}]}
                size="large"
              />
        );
    }else {
      if(this.state.isLogged){
        return(
          <Login />
        );
      }else {
        return(
          <Login />
        );
      }
    }
  }
}

还有我的UserService:

var UserService = (function() {
    return {
        /**
         * Try to get user from the storage
         */
        getUser: () => {
            return AsyncStorage.getItem('@JIT:User').then(
                function(user) {
                    if(user){
                        return user;
                    }else {
                        return false;
                    }
                }.catch(function(error) {
                console.log('There has been a problem with your fetch operation: ' + error.message);
                // ADD THIS THROW error
                throw error;
                })
            );
        },
        /**
         * Set user in the storage
         */
        setUser: (user) => {
            AsyncStorage.setItem('@JIT:User', user);
        },
    };
})();

module.export = UserService;

但是当我运行我的代码时,我会收到警告:

YellowBox.js:69 Possible Unhandled Promise Rejection (id: 0):
UserService.getUser is not a function
TypeError: UserService.getUser is not a function

我想知道为什么我会收到此错误,我该如何解决?

0 个答案:

没有答案