Recently diving into the world of TypeScript, I've been navigating my way through with relative ease. However, I've encountered a perplexing issue while working with async/await.
The problem lies within this code snippet - the 'await' keyword doesn't seem to play well with the .once() function.
async function testFunction(deviceID:string){
const returnObject:{name:string, description:string, tokens:string[]}[] = [];
const deviceRef = admin.database().ref('deviceInfo/').orderByChild('id').equalTo(deviceID);
await deviceRef.once('value', async (payload) => {
const pushObject:{name:string, description:string, tokens:string[]} = {name:"", description:"", tokens:[]};
if(payload.exists()){
const devices = payload.val();
const keys = Object.keys(devices);
for(const key of keys){
pushObject.name = devices[key].name;
pushObject.description = devices[key].description;
pushObject.tokens = await getTokens(key);
returnObject.push(pushObject);
}
console.log("Return Object 1:", returnObject);
return returnObject;
}
else{
return null;
}
})
console.log("Return Object 2:", returnObject);
return returnObject;
}
Despite using 'await' at the beginning of the deviceRef.once() function, this function consistently returns {name:" ", description: " ", tokens:[]}. Additionally, the two console logs offer insights - "Return Object 1" displays the correct object populated with data from the database, while "Return Object 2" presents an empty array. This discrepancy prompts the question - why isn't the 'await' properly waiting for the once() function to finish?
If you have any tips, suggestions, or solutions regarding this matter, they would be greatly appreciated!