我只是問這個問題來澄清并更好地理解 javascript 承諾。下面的兩個代碼看起來和我很相似,但是為什么兩者都給出了不同的結果。還有如何以.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);
異步/的await回傳正確的名稱和。然后回傳undefined
uj5u.com熱心網友回復:
是的,這正是人們所期望的。
請記住,await有效地暫停執行直到等待的操作完成。
在您使用的示例中,.then您立即回傳,因為您沒有撰寫承諾鏈,response僅在等待操作的序列完成時才回傳。相反,您立即回傳初始化的undefined值response
因此,表達你的邏輯的正確方法,否則不變,通過.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));
};
uj5u.com熱心網友回復:
因為使用async/await函式的執行被掛起(“暫停”),直到承諾被解決。因此你的函式等待結果。
但是,使用.then,您的函式將立即繼續執行 .then “塊”下方的代碼,而不是等待 resolve 的承諾。由于該回應在 .then 部分中設定之前回傳,因此仍未定義。
對于 async/await,您必須想象 return 陳述句也在 .then 塊中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396758.html
標籤:javascript 异步 谷歌云firestore 异步等待 承诺
上一篇:型別void上不存在屬性
