running queries in firebase using async / await
Asked Answered
B

1

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.

Brewer answered 1/5, 2017 at 0:17 Comment(7)
Yes, why wouldn't it be possible? Have you tried it? Do you have a problem?Apostrophe
As mentioned, the above returns a promise and not a value.Brewer
Hm, that should not be possible, await cannot return thenables. Do you use a transpiler? Have you inspected what the eventref.once('value') looks like in a debugger?Apostrophe
Works for me: runkit.com/5906914d3ff14f0012d0307e/590691ab301f4d0012938bc5Counterpart
yeah, for some reason I was sticking the .val() call in the await statement, this worked for me, too.Brewer
.once works but .on (so someRef.on('child_added')) expects a second argument. Any ideas for that?Turro
.on don't return a Promise.Mcdowell
B
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();
Bevin answered 8/12, 2017 at 11:29 Comment(8)
Totally saved me!Prolepsis
What if you need to use the value afterwards, will this tell your code to wait for value to be assigned something before proceeding?Zircon
@Zircon for your reference firebase.google.com/docs/reference/js/…Bevin
@Zircon 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.Bevin
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.Zircon
@Zircon you can just use await: var A = await eventref.once('value'); because what you're talking about is exactly what await do.Bevin
Thank you. Will it still continue processing code that doesn't require var A in this example?Zircon
@ShajeelAfzal just wrap the block in try-catchBevin

© 2022 - 2024 — McMap. All rights reserved.