3

I want to perform a Firestore query in a JavaScript function, but I'm having some difficulties with promises.

Let's say I want to get the document ID from a user. So I have created this JavaScript function:

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;
    });
}

Now when I call the function res.send(getUid("[email protected]")), it returns undefined.

Which is the correct syntax to wait until the Firestore query finsished?

2
  • 1
    What is res and where are you calling it? Commented May 18, 2019 at 14:16
  • res.send is just for sending a response in Google cloud functions. Commented May 18, 2019 at 14:19

1 Answer 1

5

get() is an async function, so you need to wrap it into an async function. Also, you are not returning anything from the getUid function - you are just returning inside a forEach parameter. If you want to get all id from the snapshot, you can use the map function.

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));
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks this really helped me! But how do I catch errors with promises?
If you're using await, you can wrap it into a try-catch statement. If you're using Promise.then, you can add a .catch handler after it.
Thanks! You helped me how to figure out promises.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.