Oli*_*via 3 javascript async-await firebase react-native google-cloud-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;
}
};
Run Code Online (Sandbox Code Playgroud)
和
//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);
});
Run Code Online (Sandbox Code Playgroud)
我正在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"
},
}
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
由于您使用的是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);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2328 次 |
| 最近记录: |