【发布时间】:2020-03-21 08:05:50
【问题描述】:
我有两种方法:
//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);
});
我是awaiting 的回复,我可以看到 doc.data() 有价值。为什么在 getAllUserData() 中看不到返回的响应?我希望这是对异步调用的愚蠢疏忽...
每个 cmets 请求的 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 以删除 then/catch 并全力以赴 async/await。
-
您在控制台中看到了什么?
-
@quicklikerabbit 更新了帖子并提供了更多详细信息。我在第一种方法中返回
undefined,但可以在第二种方法中看到文档数据。这两种方法在不同的类中。 -
@DougStevenson 我用 console.logs 更新了帖子。使用实时数据库时,我成功连接了两个文件,所以我知道这不是两者之间的连接。感觉像是异步/同步问题
标签: javascript firebase react-native async-await google-cloud-firestore