0

I have a simple Firebase query running in Node.js that returns data successfully. However, the Node.js app doesn't finish. It hangs as if it's waiting for something Firebase related to complete. What's the correct way to implement this so that the Node.js app completes?

References:

Keeping our Promises (and Callbacks) https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html

Node.js Firebase Query https://firebase.google.com/docs/reference/node/firebase.database.Query

Code:

Call my exists method to see if a product url exists in Firebase.

firebase.exists(url)
    .then(data => console.log(data))
    .catch(data => console.log(data));

Method to check if product url exists in Firebase. Returns a promise. Note the use of the Firebase once method.

public exists(url): any {
    return this.firebase.database().ref('products/').orderByChild("url").equalTo(url).once("value").then(function (snapshot) {
        return snapshot.exists();
    });
}

Code example from https://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html

// Fetch a Blog Post by ID. Returns a Promise of an actual object, not a DataSnapshot.
function getArticlePromise(id) {
  return ref.child('blogposts').child(id).once('value').then(function(snapshot) {
    return snapshot.val();
  });
}

ANSWER: Was able to resolve this by using process.exit() as suggested by Frank below.

firebase.exists(url)
    .then(data => { console.log(data); process.exit(); })
    .catch(data => console.log(data));
Matthew
  • 2,871
  • 5
  • 34
  • 59

1 Answers1

0

Your returning twice from the function, which doesn't make sense. I believe you want this:

public exists(url): any {
    this.firebase.database().ref('products/').orderByChild("url").equalTo(url).once("value").then(function (snapshot) {
        return snapshot.exists();
    });
}
Raymond Camden
  • 10,661
  • 3
  • 34
  • 68
  • This return syntax is interesting and I've updated my question to include sample code from Firebase documentation that shows this syntax being used. Making this change to the code results in error "cannot read property then of undefined" because the function no longer returns a promise. – Matthew Jul 21 '16 at 18:37
  • Ah - I think I get it - you're returning a promise with the functionality of the result in there as well. I'm sorry I 'clouded' the issue with my confusion - please excuse! – Raymond Camden Jul 21 '16 at 18:56