javascript - 从 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);
});
我正在await
响应,我可以看到 doc.data() 有价值。为什么在 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
是不正确的; 你忘了返回承诺链。(将最终更改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);
};
推荐阅读
- c# - NUnit 3 动态 ValueSourceAttribute
- dns - Plesk 自动续订 Letencrypt 使用 Google Cloud DNS
- awk - 如何使用 awk 将 PB 方法 setNull 转换为 java 等效项
- windows - Windows 上安装的 Ubuntu LTS 中 webroot 的真实路径是什么?
- css - 使用 react-use-gesture 在原点周围缩放时计算 CSS 变换位移
- c# - 使用 Moq 框架在 WPF MVVM 中测试 ViewModel
- forms - FILTER_VALIDATE_EMAIL 拒绝了一个有效的电子邮件地址
- javascript - 使用 vue-wysiwyg 上传图片的问题
- database - 每次在 Oracle 中修改特定表的数据时,如何向一组人发送邮件?
- python - 从数据框计算年龄(dob -y/m/d)