How to properly exit firebase-admin nodejs script when all transaction is completed

亡梦爱人 提交于 2019-11-30 09:15:57

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()

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);
  });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!