Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript函数中执行Firestore查询_Javascript_Firebase_Promise_Google Cloud Firestore - Fatal编程技术网

在JavaScript函数中执行Firestore查询

在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

我想在JavaScript函数中执行Firestore查询,但在承诺方面遇到了一些困难

假设我想从用户那里获取文档ID。所以我创建了这个JavaScript函数:

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
处理程序。谢谢!你帮我弄明白了承诺。