1

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?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Lucas
  • 668
  • 1
  • 5
  • 17
  • You can put `process.exit()` inside the `.then()` handler. – jfriend00 Feb 12 '21 at 15:44
  • It looks like Firestore has a `.terminate()` method to close all open streams. There is also a `.waitForPendingWrites()` method that returns a promise and I don't know if you have to call that first (and wait for completion) befoire calling `.terminate()` or if `.terminate()` handles that for you. – jfriend00 Feb 12 '21 at 15:49
  • Similar discussion here [Why is my nodejs script waiting 60 seconds before terminating](https://stackoverflow.com/questions/56314387/why-is-my-node-script-waiting-60-seconds-to-terminate-after-a-cloud-firestore-qu), though it has a different recommendation than using `.terminate()`. But apparently, there are some internal Firestore timers that cause the 60 second issue. I'm not sure if that answer is better than using `.terminate()`. – jfriend00 Feb 12 '21 at 15:54
  • So it's actually a firebase thing. Thank you for the help! – Lucas Feb 12 '21 at 15:58

1 Answers1

1

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.

Lucas
  • 668
  • 1
  • 5
  • 17