In the process of developing a Firebase function (Gist), I encountered a challenge that I'm seeking assistance for.
The function starts by querying a realtime database reference (events) using this code:
await admin.database().ref('/events_geo').once('value').then(snapshots => {
It then proceeds to iterate through all the events with this snippet:
snapshots.forEach(snapshot => {
Next, it filters events based on a specific criterion for further processing.
Subsequently, multiple queries are made to the realtime database to retrieve details related to each event like so:
await database().ref("/ratings").orderByChild('fk_event').equalTo(snapshot.key).once('value').then(snapshots => {
Data is prepared for SendGrid and the processing is finalized.
Although the data processing functions correctly, I am facing an issue where the outer 'await' command mentioned in point 1 does not wait for the inner awaits (the queries to the realtime DB) to complete. Consequently, when it's time to call SendGrid, the data is empty initially, only arriving a moment later. Reviewing the Firebase function logs below can provide more clarity:
10:54:12.642 AM Function execution started
10:54:13.945 AM There are no emails to be sent in afterEventHostMailGoodRating
10:54:14.048 AM There are no emails to be sent in afterEventHostMailBadRating
10:54:14.052 AM Function execution took 1412 ms, finished with status: 'ok'
10:54:14.148 AM <p style="margin: 1em 0px;">Super hyggelig aften :)</p><p style="margin: 1em 0px;">super oplevelse, ... long string generated
Gist displaying the concerned function
I suspect my confusion lies within the asynchronous nature of my async/await statements, particularly due to nested awaits. Although breaking down the code into smaller units might help, it could lead to complex integration of numerous awaits, making it less readable.
Therefore, I have two questions at hand. Is there a solution for this issue in the existing code structure? Additionally, what would be the most effective approach to handle such scenarios involving additional processing post retrieval from the Realtime DB?
Regards, Simon