0

I'm making an API with NodeJS and FireBase DataBase, so I want to check if the connection with the database is well established, mainly because I want to create a unit test that will verify if everything is alright with the connection. Below is my code, I have a class where I have everything related to the DB, I would like to have either a property or a method that gives me true if its connected or false if it's not. please, help.

var con = false;
var connectedRef = this.db.ref(".info/connected");
connectedRef.on("value", function (snap) {
     if (snap.val() === true) {
         con = true;
     } else {
         con = false;
     }
})
this.con = con;
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
lDiego257
  • 1
  • 3
  • What isn't working about the code you shared? Specifically: when you step through this code in a debugger, which line doesn't do what you expect it to do? – Frank van Puffelen Jan 08 '21 at 20:03
  • It always return false, i know the connection is right cause i've tried a post method and it worked. I even changed the false in the else, and it started returning true. – lDiego257 Jan 08 '21 at 20:27
  • This is no `return` in your code, so can you be more specific? My first guess is that you're trying to access `con` somewhere outside of this snippet, and that happens before `con = true;` has run. If that's indeed the case, look here: https://stackoverflow.com/a/34908497 and https://stackoverflow.com/a/40688890/209103. – Frank van Puffelen Jan 08 '21 at 22:37
  • Oh, that's a fragment from a class constructor (i was also trying to make it a method), i really didn't think about it being asynchronous, now i think the problem is what u say. The main purpose of this is to have a class where the db initializes, i also need something to confirm the connection is great (con in this case) to verify it through mocha tests. I'm looking at the links you gave and trying to implement the promise thing into the code, thank you. – lDiego257 Jan 09 '21 at 01:33
  • Glad that it was helpful – Frank van Puffelen Jan 09 '21 at 02:32

0 Answers0