Lucas
Lucas

Reputation: 738

Firestore takes a long time to end execution after executing

I have a really simple Firestore app. Besides the setting up with firebase.initializeApp(firebaseConfig);, it's only this:

db.collection("users").add({
    username: username
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});

Yet when I run this application with node index.js, it writes Document written with ID: XYZ and then it takes an additional minute to end and give control back to the terminal. I might not be using the precise terms here, so a correction would be appreciated as well.

Is there a reason for this? Should I be terminating the connection or something?

Upvotes: 1

Views: 573

Answers (1)

Lucas
Lucas

Reputation: 738

This is for a simple app, so it might not suit you.

Promise version:

If you want to keep the structure I presented in the question, then this is the final version

db.collection("users").add({
    username: "John"
})
.then( (docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch( (error) => {
    console.error("Error adding document: ", error);
})
.then( () => {
    console.log("Done");
    db.terminate();
})

Async await version:

But I'm not a fan of this whole .then() and .catch(), so I decided to convert it to an anonymous self-executing async function instead. You obviously don't need to make it self-executing or anonymous if you don't want to.

(async () => {
    try {
        const docRef = await db.collection("users").add({
            username: "John"
        });
        console.log("Document written with ID: ", docRef.id);
    } catch (error) {
        console.error("Error adding document: ", error);
    } finally {
        console.log("Done");
        db.terminate();
    }
})();

In this specific use case it might not seem that simple, but using async await makes the function sequential and easier to read, I'm my opinion.

Upvotes: 1

Related Questions