我有两种方法:
//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"
},
}
答案 0 :(得分:3)
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);
};