Javascript React Native—如何使用异步存储处理异步

Javascript React Native—如何使用异步存储处理异步,javascript,reactjs,react-native,asyncstorage,asynchronous-javascript,Javascript,Reactjs,React Native,Asyncstorage,Asynchronous Javascript,我面临异步问题: 我在firebase中创建一个用户,为其生成一个唯一的ID 我得到这个唯一的ID 我调用一个异步函数,用AsyncStorage方法持久化这个ID 问题:asyncStorage方法在我从用户创建中获取生成的ID之前被调用。如何应对 这是我的代码: class Subscription extends Component { constructor() { super(); this.state = { email: '', pa

我面临异步问题:

  • 我在firebase中创建一个用户,为其生成一个唯一的ID
  • 我得到这个唯一的ID
  • 我调用一个异步函数,用AsyncStorage方法持久化这个ID
  • 问题:asyncStorage方法在我从用户创建中获取生成的ID之前被调用。如何应对

    这是我的代码:

    class Subscription extends Component {
    
      constructor() {
        super();
        this.state = {
          email: '', 
          password: ''
        }
      }
    
      persistUserId = (userID) => {
        try {
          AsyncStorage.setItem('userId', userID); // Here, user ID is undefined
        } catch (error) {
          console.log(error.message);
        }
      };
    
      updateInputValue = (value, prop) => {
        const state = this.state;
        state[prop] = value;
        this.setState(state);
      }
    
      registerUser = () => {
        var generatedUserId = '';
    
        firebase
        .auth()
        .createUserWithEmailAndPassword(this.state.email, this.state.password) // Authentication
        .then((res) => {
            var user = { // Set Javascript Object to insert
            email: this.state.email
            }
    
            database.collection("users").add({ // Create the new user generating an ID
                'email': user.email,
            }).then(function(docRef) {
                generatedUserId = docRef.id; // Get the generated ID (The one to persist witch asyncstorage)
            }).then(function() {
                this.persistUserId(generatedUserId) // Call the AsyncStorage to persist the ID
            })
                this.props.navigation.navigate('AppPage') // Go to next page.
        })
        .catch(error => {
            alert(error.message)
        })      
      }
    

    用于持久化数据。根据react native doc。您需要使用异步等待关键字:

    _storeData = async () => {
      try {
        await AsyncStorage.setItem(
          '@MySuperStore:key',
          'I like to save it.'
        );
      } catch (error) {
        // Error saving data
      }
    }
    
    对于您的情况:

    persistUserId = async (userID) => {
        try {
          await AsyncStorage.setItem('userId', userID); // Here, user ID is undefined
        } catch (error) {
          console.log(error.message);
        }
      };
    
    
    注意:持久化数据是异步过程。这就是为什么需要使用async Wait

    您需要更新firebase,然后再捕获。使用绑定或使用箭头功能。更新版本如下:

    firebase
      .auth()
      .createUserWithEmailAndPassword(this.state.email, this.state.password) // Authentication
      .then((res) => {
        var user = {
          // Set Javascript Object to insert
          email: this.state.email,
        };
    
        database
          .collection("users")
          .add({
            // Create the new user generating an ID
            email: user.email,
          })
          .then( (docRef) =>  {
            generatedUserId = docRef.id; // Get the generated ID (The one to persist witch asyncstorage)
          })
          .then( () =>  {
            this.persistUserId(generatedUserId); // Call the AsyncStorage to persist the ID
          });
        this.props.navigation.navigate("AppPage"); // Go to next page.
      })
      .catch((error) => {
        alert(error.message);
      });
    

    我得到这个错误:可能未处理的承诺拒绝。TypeError:undefined不是对象(正在计算此.persistUserId)。不确定。检查您的错误对象。itI中很有可能没有消息字段。如果没有“try catch”,请检查该字段,同样的错误。就像persistUserId方法从未启动过一样……啊,这是因为您正在使用函数。因此,它并没有把这个纳入范围。更好的方法是使用箭头功能哇,这很棘手!很多坦克!你让我开心!!