我有两种方法:
//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() 具有值(value)。为什么我在 getAllUserData() 中看不到返回的响应?我希望这是对异步调用的愚蠢疏忽...
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
不正确;你忘了归还 promise 链。 (把最后的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);
};
关于javascript - 从 Firebase Firestore 异步返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59041871/