0

I'm not very experienced in web things, and I'm trying to make a simple api call within a class. I'm running into the very classic callback problem that new people face, and while there are tons of examples of how to handle this logic, I'm having a really hard time implementing it within a class. I'm using request. Obviously nothing below works, especially in relation to myBody, but I added it to show how I logically thought about it before worrying about asynchronous calls.

const request = require('request);

class GetData{
  constructor(){
    this.getData();
  }

  reallyGetData(){
      var myData = this.getdata;
      return myData;
  }

  getData(){
    //var myBody;
    request({'url':`https://somewebsite.com/things.json`, 'json': true }, function (error, response, body) {
        console.log('error:', error); // Print the error if one occurred
        console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received

        // Successfully returns body as expected
        console.log("From inside getData: " + body);
        //myBody = body;
        });
    //return myBody;
    }
}

The most useful link I've found explaining how I get the body outside of the getData scope is this one.

However, I'm pretty new to node (and javascript all together), and I can't seem to get the syntax for adding the callback function. Everything I try from examples is invalid syntax, so when I try adding a callback function similar to:

getData(function(result) {
    console.log(result);
}

I don't know how to implement this logic within a class.

trueCamelType
  • 2,198
  • 5
  • 39
  • 76
  • 1
    Not that you can't make it work with your `request` library, but if you do find out that you'd like to try a similar API that works with promises, I suggest you take a look at [node-fetch](https://www.npmjs.com/package/node-fetch) or [request-promise-native](https://www.npmjs.com/package/request-promise-native) – MinusFour Aug 01 '19 at 15:23

2 Answers2

2

getData() should be declared to take a function as a "first-class citizen". It might also be called a function pointer.

getData(callback) {
    ...

    callback(result);
}

When calling it, you'll use

getData(function(result) { ... });
Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
1

You can use the wait operator for it.

const request = require('request');

class Data {
    constructor() {
    }
    async getData() {
        var myBody;
        await request({ 'url': 'https://somewebsite.com/things.json', 'json': true }, (error, response, body) => {
            myBody = body;
        });
        return myBody;
    }
}

(new Data()).getData().then(data => {
    // data is the value of response
    console.log(data);
});