从Firebase Firestore异步返回数据 [英] Returning Data from Firebase Firestore Async

查看:84
本文介绍了从Firebase Firestore异步返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种方法:

//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);
    });

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

I am awaiting for the response and I can see that doc.data() has value. Why can I not see the returned response in getAllUserData()? I hope this is a stupid oversight with the async calls...

doc.data()更新

Document data: Object {
  "account": Object {
    "email": "Test142@test.com",
    "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"
  },
}

推荐答案

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

grabUserData is incorrect; you forgot to return the promise chain. (Change the final await to 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 ,因此更自然的书写方式可能是:

Since you're using async/await, a more natural way to write this might be:

//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);
    };

这篇关于从Firebase Firestore异步返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆