While browsing through various questions on this topic, I've noticed that the specific answers provided don't quite fit my situation. My query involves converting a Google Firebase RTB datasnapshot into an array of custom objects, each representing a child node and its sub children. However, I'm facing challenges with post-processing the data due to the inability to call await within a foreach loop.
After some research, I came across a solution on StackOverflow. The approach involves creating a separate function to parse the data and store promises in their own array, which is then awaited from the top level:
export async function unpack_snap(snap: any): Promise<(CustomObject[] | null)>{
const toWait: any[] = [];
console.log(JSON.stringify(snap));
await snap.forEach(async obj => {
toWait.push(obj_from_snap((obj)));
console.log(obj.key);
});
await Promise.all(toWait);
return toWait;
}
export async function obj_from_snap(co: DataSnapshot) : Promise<(CustomObject | null)>{
var newCO: CustomObject = {
val1 : co.val().val1,
val2 : co.val().val2,
Data : await GetData(co.key)
};
console.log(`Data: ${newCO.Data}`)
return newCO;
}
export async function getData(key: String) Promise<(String | null)>{
...
}
However, this setup results in an array with empty objects ([{}]). The forEach loop only runs once even though the JSON snapshot contains multiple valid child nodes. Similarly, logging of newCO.Data within the helper function doesn't seem to trigger repeatedly as expected.
I am puzzled as to why this process isn't looping as intended. Additionally, if I were to return the toWait[] array, would it include all the CustomObjects generated by the helper function? If not, what alternative method can provide me with an array of distinct CustomObjects from individual function calls?
Any suggestions or insights? Your assistance is greatly appreciated.
UPDATE
In an attempt to troubleshoot, I simply added a key printing loop within forEach:
await snap.forEach(async obj => {
console.log(obj.key);
});
return null;
Despite having multiple child nodes, only the first key gets printed before the function exits prematurely, returning null. This behavior persists regardless of the number of child nodes present. It seems like the issue lies elsewhere, unrelated to Promise.all(). Any thoughts on this puzzling outcome?