从Firebase Firestore异步返回数据

问题描述 投票:0回答:1

我有两种方法:

//authContext.js
const getAllUserData = (dispatch) => { 
    return async (userId)=>{
    try{
        const response = await config.grabUserData(userId);
        console.log('should be an array of user data: ' + response + ', ' + JSON.stringify(response)); //should be an array of user data: undefined, undefined
        for(ud in response){
            await AsyncStorage.setItem('' + ud, '' + response[ud]);
            dispatch({type: 'user_data', payload: response});
        }
    } catch(e){
        dispatch({type: 'add_error', payload: '' + e});
    }
    return dispatch;
    }
};

//config.js 
grabUserData = async (userId) => {
    var db = firebase.firestore();
    var userId = firebase.auth().currentUser.uid;
    var docRef = db.collection("Users").doc(userId);
    await docRef.get().then(function(doc) {
      if (doc.exists) {
          console.log(doc.data()); //see below for doc object
          return doc.data();;
      } else {
          console.log("No such document!");
      }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });

我正在await响应,我可以看到doc.data()具有价值。为什么在getAllUserData()中看不到返回的响应?我希望这是对异步调用的愚蠢监督...

每个评论请求的doc.data()个更新

Document data: Object {
  "account": Object {
    "email": "[email protected]",
    "password": "password142",
    "phone": "9999999999",
  },
  "id": "test1298347589",
  "info": Object {
    "test123": Array [],
    "test345": "",
    "fullName": "Test 142",
    "interests": Array ["test"],
  },
  "matches": Object {
    "queue": Object {
      "id": "",
    },
  },
  "preferences": Object {
    "ageRange": Array [],
    "distance": 47,
    "lookingFor": Array ["test",],
    "prefData": "test"
  },
}
javascript firebase react-native async-await google-cloud-firestore
1个回答
1
投票

grabUserData不正确;您忘了归还承诺链。 (将最终的await更改为return):

//config.js 
grabUserData = async (userId) => {
    var db = firebase.firestore();
    var userId = firebase.auth().currentUser.uid;
    var docRef = db.collection("Users").doc(userId);
    return docRef.get().then(function(doc) {
      if (doc.exists) {
          console.log(doc.data()); //see below for doc object
          return doc.data();
      } else {
          console.log("No such document!");
      }
    }).catch(function(error) {
        console.log("Error getting document:", error);
    });

由于您使用的是async / await,更自然的书写方式可能是:

//config.js 
grabUserData = async (userId) => {
    var db = firebase.firestore();
    var userId = firebase.auth().currentUser.uid;
    var docRef = db.collection("Users").doc(userId);
    try {
        var doc = await docRef.get()
        if (doc.exists) {
            console.log(doc.data()); //see below for doc object
            return doc.data();
        } else {
            console.log("No such document!");
        }
    } catch (error) {
        console.log("Error getting document:", error);
    };
© www.soinside.com 2019 - 2024. All rights reserved.