I'm trying to get the data from a firebase db entry. The use case is as follows: I will query a web API with a latitude, longitude and radius which a query with the GeoQuery library, this library provides a database structure associated to a database entry key. I use the key_entered event manager to trigger all of the matching location database entries.
I now want to check whether the associated datas timestamp is newer than now but I got some struggles getting the data out of the Promise. I'm aware that the code below is not working due to the asynchronous nature of Promises, but is there any possibility to associate the data of once with a variable, e.g. waiting for the Promise to return something until continuing (like await etc.)?
I'm fully aware of the asynchron nature of node.js here but I have to return the data to the res.send since it provides an enclosed API call.
I also already used a callback function to call inside the db query promise and tried to associate it to data, that did not work as well.
function queryGeoLocation(req, res) {
try {
const lat = parseFloat(req.params.lat);
const long = parseFloat(req.params.long);
const radius = parseFloat(req.params.radius);
let geoQuery = geoFire.query({center: [lat, long], radius: radius});
data = new QueryData(); //Use this to handle data asynchronously
geoQuery.on("key_entered", (key, loc, dist) => {
isFutureEvent = false;
admin.database().ref("/events/").child(key).once("value").then((snapshot) => {
if(Date.parse(snapshot.val().date) >= Date.now())
isFutureEvent = true;
}).catch(() => {
});
console.log(isFutureEvent);
if (isFutureEvent){
data.add(key, loc, dist);
}
});
// When ready directly cancel the query provider and return data (since we only want to read once)
geoQuery.on('ready', () => {
geoQuery.cancel();
res.send(data.getData());
});
} catch (err) {
res.status(500).send("Error: " + err);
}
}
via domna
No comments:
Post a Comment