41

Appreciating that firebase has added support for promises, is there a way to run a query like the following inside of an async function?:

const eventref = this.db.ref('cats/whiskers');
const value = await eventref.once('value')

Running the above returns a promise for value, I'm hoping to get the json blob that is stored at cats/whiskers.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
fox
  • 15,428
  • 20
  • 55
  • 85

1 Answers1

71

The result of value is a snapshot, we need 1 more step to get the value. This should be like:

const eventref = this.db.ref('cats/whiskers');
const snapshot = await eventref.once('value');
const value = snapshot.val();
Hank Phung
  • 2,059
  • 1
  • 23
  • 38
  • Totally saved me! – zeckdude Sep 02 '18 at 03:46
  • What if you need to use the value afterwards, will this tell your code to wait for `value` to be assigned something before proceeding? – Badrush Dec 04 '18 at 19:13
  • @Badrush for your reference https://firebase.google.com/docs/reference/js/firebase.database.Query#once – Hank Phung Dec 05 '18 at 06:19
  • @Badrush `value` event can be used to retrieve the current value of a specific node in your database using `once` or can be used to subscribe to changes on a specific node in your database using `on`. – Hank Phung Dec 05 '18 at 06:25
  • What I mean is. Let's say I need to retrieve the snapshot and store it inside of `var A`... then I have a code that takes `var A` and displays it. Is there a way to tell my code to wait until the snapshot is finished retrieving so that `var A` wont be `undefined`? I do know you can use `.then` but sometimes that makes the code very messy. Especially if `var A` isn't used until much later in the code. – Badrush Dec 05 '18 at 17:04
  • 2
    @Badrush you can just use await: `var A = await eventref.once('value');` because what you're talking about is exactly what `await` do. – Hank Phung Dec 06 '18 at 09:22
  • Thank you. Will it still continue processing code that doesn't require `var A` in this example? – Badrush Dec 06 '18 at 16:37
  • @ShajeelAfzal just wrap the block in try-catch – Hank Phung Oct 21 '19 at 08:20