23

Is there anyway to check if all firebase transaction is completed in firebase-admin nodejs script, and properly disconnect from firebase and exit the nodejs script?

Currently, the firebase-admin nodejs script will just keep running even after all the transaction has been completed.

Andrew See
  • 1,062
  • 10
  • 21

2 Answers2

38

If you're keeping track of all the promises and they complete successfully, what's happening is that the app is keeping a connection open, you can kill the app, by using:

app.delete()

For example if you used the default app you can do this:

firebase.app().delete()
Dima
  • 672
  • 9
  • 9
5

The DatabaseReference.transaction() method returns a promise which is fulfilled when the transaction is completed. You can use Promise.all() method to wait for any number of these transaction promises to complete and then call process.exit() to end the program.

Here is a full example:

    var admin = require("firebase-admin");

    // Initialize the SDK
    var serviceAccount = require("path/to/serviceAccountKey.json");
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
      databaseURL: "https://<DATABASE_NAME>.firebaseio.com"
    });

    // Create two transactions
    var addRef = admin.database().ref("add");
    var addPromise = addRef.transaction(function(current) {
      return (current || 0) + 1;
    });

    var subtractRef = admin.database().ref("subtract");
    var subtractPromise = subtractRef.transaction(function(current) {
      return (current || 0) - 1;
    });

    // Wait for all transactions to complete and then exit
    return Promise.all([addPromise, subtractPromise])
      .then(function() {
        console.log("Transaction promises completed! Exiting...");
        process.exit(0);
      })
      .catch(function(error) {
        console.log("Transactions failed:", error);
        process.exit(1);
      });
Giorgi Gvimradze
  • 1,714
  • 1
  • 17
  • 34
jwngr
  • 4,284
  • 1
  • 24
  • 27