Weird behavior observed with NativeScript Firebase and ES6 promises

My goal is to connect 2 Firebase queries using promises, as I require the result of the first query in order to execute the second one. Below are the details of the 2 queries:

QUERY FOR VALUE A:

    private getValueA(){
    var queryEvent = (result):void  =>{
        console.dump(result);
        this._valueA = result.value;
    }
    return firebase.query(
        queryEvent,
        FirebaseValueAPath, 
        {
            singleEvent : true,
            orderBy : {
                type: firebase.QueryOrderByType.CHILD,
                value: 'since' 
            }
        });
    }

QUERY FOR VALUE B:

    private getValueB{

        let FirebaseValueBPath :string = this._valueA
        var queryEvent = (result) :void =>{
            console.dump(result);
            if(result.value){
                this._valueB = result.value;
            }
        }
        return firebase.query(
            queryEvent,
            FirebaseValueBPath,
            {
                singleEvent : true,
                orderBy : {
                    type    : firebase.QueryOrderByType.CHILD,
                    value   : 'since'
                }
        });
    }
}

Next, I attempt to link them together by implementing the following :

constructor(){
    this.getValueA().then(
     (success) :void => {
    this.getValueB();
   });
}

The outcome reveals some issues:

  1. Oddly enough, console.log(result) within the getValueB function is displayed before the log from inside the getValueA function (why??)
  2. this.valueA is undefined in getValueB, rendering my query ineffective
  3. The application crashes

Where did I go wrong in my code? Is there a different method I should be utilizing for this scenario? Appreciate your assistance on this matter :)

Answer №1

Utilizing promises requires resolving the result within your callback function. Check out the code snippet provided below:

class DataFetcher {
    constructor() {
        this.fetchDataA()
            .then(resultA => this.fetchDataB(resultA));
    }

    fetchDataA() {
        return new Promise<string>((resolve, reject) => {
            firebase.query(
                (result) => {
                    resolve(result.value); // Resolving to return the result
                },
                FirebaseValueAPath, 
                {
                    singleEvent: true,
                    orderBy: {
                        type: firebase.QueryOrderByType.CHILD,
                        value: 'since' 
                    }
                }));
        });
    }

    fetchDataB(valueA: string) {
        return new Promise<string>((resolve, reject) => {
            firebase.query(
                (result) => {
                    resolve(result.value);  // Resolving to return the result
                },
                valueA, 
                {
                    singleEvent: true,
                    orderBy: {
                        type: firebase.QueryOrderByType.CHILD,
                        value: 'since' 
                    }
                }));
        });
    }
}

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

What is the best way to showcase a file edited in Emacs within Atom?

The coding project I'm working on is built with Typescript, but I don't believe that's relevant. I've noticed that Emacs has a unique approach to indentation. According to the documentation, in Text mode and similar major modes, the TAB ...

Troubleshooting: ng-model items not appearing in AngularJS $scope object

Currently, I am facing an issue while attempting to create a table where users can edit each row and save their changes. After pressing save, only some elements in the row are being sent, and I am having trouble with this. Any help or insights on how to re ...

Looking to obtain an audio file from a URL in Node.js?

Is it possible to save an audio file from a URL to a local directory using Node.js? Below is the code I attempted: var http = require('http'); var fs = require('fs'); var dest = 'C./test'; var url= 'http://static1.grsite ...

How to dynamically insert variables into a separate HTML file while creating a VS Code extension

Currently working on a vscode extension, I'm facing an issue with containing the html in a string (like this: https://github.com/microsoft/vscode-extension-samples/blob/main/webview-view-sample/src/extension.ts). It leads to a large file size and lack ...

Issues with the bootstrap 4 modal update

I am currently working on an app in Spring Boot with JSP for the frontend, and I have encountered a specific issue: In my application, there is a table with multiple rows where I can click a button to update each row as needed. When I click on one row and ...

Tailwind does not display font sizes using random values

I am attempting to adjust the size of a span element based on a number from a variable: export default async function Tags() { const tags = await getTags(); return ( <div> <Suspense> <div className="flex flex-wrap ...

IDE flags an error with TypeScript type declarations

Here is how my type definition looks: export type AuthType = boolean | { roles: string[]; assistant?: string[] } | (() => void); Now, I need to check the type of the auth variable and assign a value or execute a function in this line of code: req.all ...

Updating a List Conditionally in React

Hello there! I am relatively new to the world of React and currently trying to grasp the concept of modifying elements within a list. Below, you'll find a straightforward example that illustrates my current dilemma. const numbers = [1, 2, 3, 4, 5]; / ...

Encountering vulnerabilities during the deployment of my React App using NPM has presented a challenge

Just starting out with React Js and seeking some guidance. I've developed a small React app that filters team members based on text input, and it's running smoothly in the development environment when I start NPM. Please review my project and poi ...

Switching to a different view in a React Native application

I am encountering difficulties while navigating between pages in my React Native application. Whenever I try to use the button, an error message pops up saying: TypeError: undefined is not an object (evaluating '_this.props.navigation'). My app c ...

Guide on parsing a JSON array passed from JavaScript using json_decode?

I am attempting to send JSON string encoded data to the PHP backend. In order to achieve this, I am utilizing a GET parameter with URL encoded JSON data in the form of an array similar to this: ["mystring1","mystring2"] However, when I try to decode it us ...

Can AJAX be considered a backend tool for retrieving data from servers?

I'm curious to find out if ajax is primarily used as a backend technology for retrieving data or if it's mainly considered a frontend tool. My attempts to research this on Google have not yielded a definitive answer. ...

What could be causing the res.sendfile() method to fail when invoked through a jQuery ajax call?

Problem: The first ajax call in the main.js is functioning correctly, but there seems to be an issue with the second one. Although it appears to be working initially, I suspect that there may be a bug present. Upon clicking the button, I am able to access ...

Error message in Angular 2, Problem found in inline template while utilizing eval() function

<li *ngFor="let pdfifRecord of pdf.ifRecord;let i=index"> <p>{{eval(pdfifRecord.labelMsg)}}</p> </li> I need to show the output of the eval function. Encountering an error message: Error in inline template c ...

Automatically choose radio buttons within an li element in a loop

Hey there, I'm new to SO and this is my first question. As a bit of a newbie, I found this jquery code snippet on another SO answer that I want to use. The function I'm aiming for is the same, but the markup structure in my HTML is different bec ...

In the realm of Typescript Angular, transferring the value of an object's property to another property within the

I'm working with a large TypeScript object and I am hoping to automate certain parts of it to streamline my workflow. myObject = [ { id: 0, price: 100, isBought: false, click: () => this.buyItem(100, 0) } buyItem (it ...

How do I connect to a different application's view?

When working with a view that has tiles, I am looking to click on one of them and be directed to a different application that I have created. In typical cases, I would specify the view folder for navigation. However, when attempting something similar for ...

When the mouse drags across the empty space, the force graph continually jumps

I have some questions. I utilized a force graph and added zoom functionality to it. However, when I drag the mouse over the blank area, the force graph keeps jumping erratically. like this Is there a way to prevent the graph from jumping? Thank you. ( ...

Enum-Based Object Indexing

The structure I am currently working with is as follows; import data from "../data.min.json"; export enum TileType { tree = 'tree', rock = 'rock' } interface MapTile { walkable: boolean; positions: number[][]; } exp ...

Adding Rows to a DataTables Table

I am currently working on dynamically adding <tr/> tags to a DataTable, but I am struggling to find detailed documentation on how the process of "adding TR" is meant to be executed. Below is the setup of my DataTable: $("#Grid").DataTable({ state ...