我问这个问题只是为了澄清并更好地理解 javascript promise 。下面的两个代码对我来说看起来非常相似,但是为什么两者给出了不同的结果。还有如何以.then方式获取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();
.然后
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 返回正确的名称,.then 返回未定义
最佳答案
是的,这正是人们所期望的。
请记住,await
有效地暂停执行,直到等待的操作完成。
在使用 .then
的示例中,您会立即返回,因为您没有编写 promise 链,以便仅在等待的操作序列完成时才返回 response
。相反,您会立即返回初始化 response
的 undefined
值
因此,通过 .then
表达逻辑的正确方法(否则不改变)将是
const getFieldValue = (collection, userid) => {
let response;
return firestore() // notice the return here! This is vital
.collection(collection)
.where("userid", "==", userid)
.get()
.then((querySnapshot) => {
querySnapshot.docs.find((doc) => {
const { name } = doc.data();
response = name;
});
})
.then(() => response) // notice how we resolve our promise chain with the value ultimately assigned
.catch((e) => console.log(e));
};
关于javascript - 为什么 async/await 会产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70503710/