在JavaScript函数中执行Firestore查询
我想在JavaScript函数中执行Firestore查询,但在承诺方面遇到了一些困难 假设我想从用户那里获取文档ID。所以我创建了这个JavaScript函数:在JavaScript函数中执行Firestore查询,javascript,firebase,promise,google-cloud-firestore,Javascript,Firebase,Promise,Google Cloud Firestore,我想在JavaScript函数中执行Firestore查询,但在承诺方面遇到了一些困难 假设我想从用户那里获取文档ID。所以我创建了这个JavaScript函数: function getUid(email) { db.collection("users").where("email", "==", email) .get() .then(function(querySnapshot) { querySnapshot.forEach(function(do
function getUid(email) {
db.collection("users").where("email", "==", email)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
return doc.id;
});
})
.catch(function(error) {
return error;
});
}
现在,当我调用函数res.send(getUid(“user@example.com)
,它返回未定义的
在Firestore查询找到之前,哪种语法是正确的?get()
是一个异步函数,因此需要将其包装成一个async
函数。另外,您没有从getUid
函数返回任何内容-您只是在forEach
参数内返回。如果要从快照中获取所有id
,可以使用map
功能
async function getUids(email) {
const db = admin.firestore();
const querySnapshot = await db.collection("users").where("email", "==", email).get();
const uids = querySnapshot.docs.map((doc) => { return doc.id });
return uids;
}
exports.yourFunction = functions.http.onRequest(async (req, res) => {
const email = // ...
res.send(await getUids(email));
});
什么是res
,你在哪里调用它?res.send
只用于在谷歌云函数中发送响应。谢谢这真的帮助了我!但是我如何用承诺捕捉错误呢?如果您使用的是await
,您可以将其包装成try-catch
语句。如果您使用的是Promise.then
,则可以在其后面添加.catch
处理程序。谢谢!你帮我弄明白了承诺。