Leveraging async/await in Firebase functions along with the once() method

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!

Answer №1

element, you have two options when using once():
  1. Retrieve the data by utilizing the promise returned.
  2. Alternatively, pass a callback function as the second argument to access the data from the query.
It is recommended that if you are working with async/await, stick with option 1 for simplicity. Currently, it seems like you are mixing both approaches, which might lead to confusion. Avoid passing a callback function to once() if you plan on using the returned promise. This will ensure a more streamlined process when using async/await.
const payload = await deviceRef.once('value')
if (payload.exists()) { ... }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine the type of function arguments based on provided hints in TypeScript

It's common to encounter situations like this where TypeScript struggles to infer types due to lack of context. Is there a way to explicitly declare the type of function for the compiler? router.get('/get', imget); router.get('/send&a ...

What advantages does utilizing Jasmine Spy Object provide in Angular Unit Testing?

I have a question regarding unit testing in Angular using Jasmin/Karma. Currently, I am working with three services: EmployeeService, SalaryService, and TaxationService. The EmployeeService depends on the SalaryService, which is injected into its constru ...

The CSS formatting is not being properly applied within the innerHTML

I have a scenario where I am trying to display a Bootstrap card using innerHTML in my TS file, but the styles are not being applied to this content. I suspect that the issue might be because the styles are loaded before the component displays the card, cau ...

Steps for removing the console warning message: "The use of enableRowSelect has been deprecated. Instead, please utilize rowSelection."

) I have integrated React Data Grid from https://adazzle.github.io/react-data-grid/ multiple times in my application. One thing I noticed is that there is a console warning related to a prop called "enableRowSelect" which indicates whether the prop is bein ...

Unable to incorporate node-vibrant into Angular 7 project

Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...

Performing an asynchronous POST request in JavaScript

Hey there, I successfully managed to implement a post request using ajax for my submit functionality. However, I am now looking to make this asynchronous to account for any delays in processing by my php file. Unfortunately, I am struggling to figure out h ...

Unlocking the Power of FusionAuth in NativeScript: A Guide

While attempting to utilize a library based on nativescript documentation, I encountered an issue where certain modules like net and tls were not being automatically discovered. After using npm install to include tls and net, the problem persisted with t ...

Tips for choosing a subset of objects within a larger array of objects and generating a new array from them?

I am working with an array of 3586 objects, each containing various products. How can I create and store a new array that only includes the products from a specific index? console.log listarPorReferencia() { this.linxService.listarPorReferencia().subs ...

Tips on utilizing storage.set() within google.maps.events.addListener(marker, 'dragend', function() { }); in Ionic 3

google.maps.event.addListener(Marker, 'click', (function(Marker) { return function() { this.storage.set('mylocation', this.Marker.getPosition()); } })(Marker)); polyfills.js:3 Uncaught TypeError: Cannot read property 'set ...

Leverage glob patterns within TypeScript declaration files

Utilizing the file-loader webpack plugin allows for the conversion of media imports into their URLs. For example, in import src from './image.png', the variable src is treated as a string. To inform TypeScript about this behavior, one can create ...

Issue with loading React Router custom props array but custom string works fine

I am facing an issue with my ReactTS-App where I pass a prop via Router-Dom-Props to another component. The problem arises when I try to use meal.food along with meal.name, or just meal.food alone - it doesn't work as expected. Uncaught TypeError: mea ...

Cross-origin error triggered by using an external API within a ReactJS application

I'm facing a common CORS issue in my application while trying to call an API. The API I am attempting to access can be found here: https://github.com/nickypangers/passport-visa-api Below is the code snippet used for making the API call: const getVi ...

A step-by-step guide to showcasing dates in HTML with Angular

I have set up two datepickers in my HTML file using bootstrap and I am attempting to display a message that shows the period between the first selected date and the second selected date. The typescript class is as follows: export class Datepicker { ...

Develop an asynchronous function that can fetch a result at a later time within an Express route

I need to retrieve an Excel file from Box.com using their API and then convert the Excel data into JSON format. Afterwards, I plan to display this JSON data using Express and Handlebars. Below is the function I've created for fetching the Excel file ...

The error message indicates a compatibility issue between parameters 'r' and 'a'

Attempting to reproduce the code found in this blog post, but encountering some perplexing errors. import { option, identity, apply } from 'fp-ts'; import type { Kind, URIS } from 'fp-ts/HKT'; import { pipe } from 'fp-ts/lib/functi ...

I've tried using a ControlValueAccessor, but for some reason the value isn't getting passed to the form

Currently, I am experimenting with reactive forms in Angular, and I'm encountering difficulties with updating the form from custom components. As an example, take a look at the date-input component created using flatpickr in the linked Plunker demo. ...

Unable to show the input's value

Need help in taking user input to display calculated values //html <div class="empty"> <h5> Enter Empty Seats </h5> <ion-item> <ion-input placeholder="Enter Number of Empties.." type="number" name="emptySeats" [( ...

How can I implement dynamic styling for the rows in the PrimeNG table?

I have the MyObject.ts file with the following properties: name: String rowStyle: String In addition, I have a MyComponent.ts file containing: myObject1: MyObject = new MyObject(); myObject2: MyObject = new MyObject(); myObjectList: MyObject[] = []; myO ...

Getting a list of the stack resources available in cloudformation using TypeScript

My team is developing an application that will deploy multiple stacks to AWS. One of these stacks is called SuperStar, and it can only exist once per AWS account. I am currently exploring how our TypeScript CDK can retrieve a list of stacks from CloudFor ...

The Angular service retrieves only the default values

I'm currently following an Angular tutorial and encountering some issues. Problem #1: The problem arises when using two services, recipe.service.ts (handles local data manipulation) and data-storage.service.ts (stores data in Firebase). When the getR ...