Reputation: 1
await returns [Function] instead of value
Trying to return the values of a query from firebase by making use of the async and await function. Results returned are either [Function] or Unhandled Promise Rejection Warnings. New to promises, async and await but I've tried the basic examples on a few websites, most having the resolve and reject parameters, which I assume should be the same as the firebase promises.
I tried 2 different version, both with incorrect results.
get_all_users:async function(){
ref = db.ref("/user_data");
const value = await ref.orderByKey().on("child_added", function(data){});
console.log(value.val().name);
}
returns UnhandledPromiseRejectionWarning
function get_async_users(){
ref = db.ref("/user_data");
ref.orderByKey().on("child_added", function(data) {
return data.val().name;
});
}
returns undefined
Expected either one to return the names from the query.
Upvotes: 0
Views: 80
Reputation: 138257
on
is for listening to all events that ever get triggered. Therefore it does not return a Promise, as a Promise represents a single value being available, and as it does not return a Promise, you can't await
it (or at least: it doesn't make sense to do so, its a no-op).
If you want to wait for the first occurence, there is once
, which also returns a promise that can be await
ed.
Concerning the UnhandledPromiseRejection: You should always wrap your asynchronous code into a try / catch
(inside an async function
), or attach a .catch
to the upmost promise in the chain, then you can handle those errors correctly.
Upvotes: 1