I’m just asking this question to clarify and get a better understanding at javascript promises. The following two codes look very similar to me, but why both gives different results. Also how to get the result of async/await function in .then way. Thanks.
async/await
const getFieldValue = async (collection, userid) => {
let response;
const querySnapshot = await firestore()
.collection(collection)
.where("userid", "==", userid)
.get();
querySnapshot.forEach((doc) => {
const { name } = doc.data();
response = name;
});
return response;
};
async function fetchData() {
const name = await getFieldValue("Users", userid);
console.log("name", name);
}
fetchData();
.then
const getFieldValue = (collection, userid) => {
let response;
firestore()
.collection(collection)
.where("userid", "==", userid)
.get()
.then((querySnapshot) => {
querySnapshot.docs.find((doc) => {
const { name } = doc.data();
response = name;
});
})
.catch((e) => console.log(e));
return response;
};
const name = getFieldValue("Users", userid);
console.log("name", name);
async/await returns correct name and .then returns undefined