Is there a way to invoke a different function within a class from a callback function in an HTTP request?

Having an issue with my HTTP GET request function in the "CheckPrice" class. When trying to call another function within the class callback, it's showing as undefined. Any suggestions?

const got = require("got")

class PriceCheck {
    constructor() {
        this.lastTick;
        this.requestTimerHandle;
    }

    /**
     * Calculate absolute percent difference between two numbers
     */
    absolutePercentDiff(firstNum, secondNum) {
        return (Math.abs(firstNum - secondNum) / ((firstNum + secondNum) / 2)) * 100;
    }

    // More functions go here...

    async requestRate(first, second, threshold) {
        console.log("requesting conversion rate between " + first + " and " + second)
        
        try {
            const response = await got('https://company.com/api' + first + '-' + second);
            console.log(response.body);
            let currentTick = JSON.parse(response.body);
            this.alertDifference(currentTick, threshold);

        } catch (error) {
            console.log(error.response.body);
        }
    }

}

module.exports = {PriceCheck: PriceCheck}

The output gives:

(node:1282) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'body' of undefined

In my app.js:

priceChecker = new PriceCheck();
priceChecker.requestRateInterval("BTC", "USD", 0.01, 5000);

Answer №1

It is important to remember that in your constructor, you need to ensure that your instance methods are bound so that the this keyword has a proper value within the context of that method. This can be achieved by binding the instance methods as shown below:

constructor() {
    this.lastTick;
    this.requestTimerHandle;

    // Binding instance methods
    this.calculateTotal = this.calculateTotal.bind(this);
    this.displayDetails = this.displayDetails.bind(this);
    this.updateInfo = this.updateInfo.bind(this);
    this.processData = this.processData.bind(this);
}

If you fail to bind your instance methods, the this keyword will be undefined within the scope of the method.

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

Converting JSON data from a PHP variable into a jQuery array: What you need to know

I attempted to retrieve addresses using the postcode and applied the getaddress.io site API with PHP. This resulted in a JSON dataset stored in the PHP variable $file. Now, I am tasked with converting this JSON result into a jQuery array. { "Latitude":-0. ...

Formulate a targeted search request according to the selected radio button option

I'm working on a form that looks like this: <form> <input type="text" id="searchedWord" class="form-control form-control-lg" value="words here"/> <button type="submit" id="f ...

Modify the property of an element within an array

I have an array of objects with a certain property. I need to perform some mathematical operations on this property and return a new array. However, my current approach does not seem to be working as expected. array.map(el => { el.count * 2; r ...

Learn the process of making an http request in Angular 8 by utilizing FormData

After struggling with sending data from my html form to the backend server using Angular HTTPClient, I realized that my code was not working as expected. HTML Form <form class="border text-center p-5 reg-frm" [formGroup]="ContactusForm"> <l ...

Cracking the Code: Unleashing the Art of Parsing JSON with Dart's Dynamic Object

Can anyone help me with mapping this JSON in Dart? I received this JSON as the response.data from a get request made using the Dio library in Flutter. [ { "getPlayersFilterResult": { "Players": [{p1},{p2},..] } }, ...

Why does a React error keep popping up when trying to set a background-image in my CSS?

I've been working on my React project and I can't figure out why I keep encountering this error. I double-checked the URL paths and made sure they were named correctly, yet the error persists. Here is a snippet of my CSS: background-image: url ...

What's better in React: using pure components or non-pure components? Is it okay to fetch data in componentDidMount or

Exploring React in Meteor has led me to observe two distinct approaches... Take the meteor leaderboard example, where a list of players displays their names and scores. The pure approach involves fetching all players and passing them into the playersList ...

What steps do I need to take to ensure that this Regex pattern only recognizes percentages?

I am attempting to create a specific scenario where I can restrict my string to three digits, followed by a dot and two optional digits after the dot. For example: 100.00 1 10.56 31.5 I've developed a regex pattern that allows me to filter out any ...

How to store data retrieved with $http.get in AngularJS into a variable

I am attempting to assign data retrieved from $http.get to a variable in my controller. $http.get(URL).success(function (data) { $scope.results = data; console.log('results within $http.get :'+ $scope.results); }); console.lo ...

Check if the value is a string and contains a floating point number; if so, parse and format the float

I need to work on formatting decimal values returned by an API that only responds with strings. The requirement is to add a leading zero but no trailing zeros to any decimal value in the string. If the value is not a float, it should remain unchanged. For ...

Vuetify's <v-text-field> feature automatically clears the input after selecting a result from Google Maps autocomplete

A dilemma I'm facing is with a page that has a <v-text-field> containing GoogleMaps autocomplete. The problem arises when Vuetify clears the input once an address is selected by the user. I have discovered that this complication is connected to ...

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

Adding an arrow to a Material UI popover similar to a Tooltip

Can an Arrow be added to the Popover similar to the one in the ToolTip? https://i.stack.imgur.com/syWfg.png https://i.stack.imgur.com/4vBpC.png Is it possible to include an Arrow in the design of the Popover? ...

This error is thrown when trying to access the property 'message' of an undefined value

I'm currently working on adding an AJAX contact form to my website. However, I've run into a problem where when I try to submit the form, I encounter the following error in Google Chrome: "Uncaught TypeError: Cannot read property 'message&a ...

What's the best way to iterate through multiple objects within <td> tags using Vue.js?

I have an Array filled with multiple Objects, and now I am interested in iterating through each object as a <tr> within a <table>. I have successfully achieved this. However, some of these objects might contain nested objects. In such cases, I ...

ESLint is reminding you that the `parserOptions.project` setting must be configured to reference the tsconfig.json files specific to your

Within my NX Workspace, I am developing a NestJS-Angular project. Upon running nx lint, an error is triggered with the following message: Error: A lint rule requiring the TypeScript type-checker to be fully available has been attempted, but `parserOptions. ...

Let the Vuejs transition occur exclusively during the opening of a slide

Trying to implement a smooth transition when the toggle button is clicked. Successfully applied the transition effect on the slider, but struggling to animate the text inside the div.hello class upon sliding open. <transition name="slide"> <a ...

ExpressJs res.json throwing error - Headers cannot be set after they have already been sent

In my current project using ExpressJS, I have a specific route set up like this: router.route('/monitor') .all(function (req, res, next) { next(); }).get(monitor.monitorServers); There is also a controller named 'monitor' which co ...

Is bower install failing to detect a local npm package?

After running bower install, I encountered the following error message: $ bower install module.js:340 throw err; ^ Error: Cannot find module 'minimist' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._l ...

Efficiently handling multiple responses in Express.js per single request

Currently exploring Node.js and working on a bot utilizing Dialogflow. I am aiming to establish a straightforward process: Step 1: Dialogflow sends a POST request with parameter param1 Step 2: My application replies with a waiting message (e.g., "your re ...