0

I have the following snippet that gets data in json format but I want to return the data rater than just printing it out in console.

var request = require('request');

var headers = {
  'Connection': 'keep-alive',
  'Accept': 'application/json, text/plain, /',
  'User-Agent': 'Mozilla/5.0 (Macintosh; Ontel Mac OS X 11_2_3) AppleWebKit/537/36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36',
  'Content-Type': 'application/json',
  'Accept-Language': 'en, zh-TW;q=0.8,en-US;q=0.7'
};

const PublicKeyBase58Check = "";
const Username = "elonmusk";

var dataString = '{"PublicKeyBase58Check":"' + PublicKeyBase58Check + '","Username":"' + Username + '"}';

var options = {
  url: 'https://api.bitclout.com/get-single-profile',
  method: 'POST',
  headers: headers,
  body: dataString
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
    var profile = JSON.parse(body);
    return profile;
  } 
};

request(options, callback);

What change do I need to make in request function() so that I can access the json object profile from the callback function and use it for later purposes?

Somdip Dey
  • 3,346
  • 6
  • 28
  • 60
  • Use the result inside the callback or call some function from within the callback and pass the result to it as an argument. You can't return it directly because it's asynchronous and the function has already returned long before you get the value. You can communicate it back with a callback or a promise or just use the result inside the callback itself. FYI, you should not be writing any new code with the `request()` library because it has been deprecated. I'd suggest the `got()` library instead which is based on promises which is a better interface. – jfriend00 Apr 27 '21 at 04:28
  • @jfriend00 I am new to Node JS. I was hoping if u could make the necessary changes to the above code and post as an answer if possible? thanks a ton. – Somdip Dey Apr 27 '21 at 04:34

2 Answers2

0

You need to write asynchronous code using async/await or Promises or Observables or any npm package that handles asynchronous requests. The npm package that you used (request) is deprecated. In case you want to continue using the same, the rest of the execution can be added inside the function. No need to return the value.

function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
        var profile = JSON.parse(body);
        /*
         Write rest of the code here
        */
    }
};

request(options, callback);`
MidKar
  • 46
  • 4
-1

if i understood correctly, you are getting your data in JSON notation from server side and you want to store it for further use?

Your callback already has a profile: make a global variable var incoming_data =[];

Every time your callback returns a result store it to array:

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
    var profile = JSON.parse(body);
    data.push[{incomingData:profile}];
    return profile;
  } 
};

Once it is globally assigned you will have an array with all results for further usage.

Keep in mind that all setup is asynchronous so maybe is a good practice to use promises.

function callback(error, response, body) {
var promise = new Promise(function(resolve, reject) {  
      
      if (!error && response.statusCode == 200) {
        console.log(body);
        var profile = JSON.parse(body);
        data.push[{incomingData:profile}];
        resolve(profile);
        return profile;
        // you can also do: return resolve(profile);
      } 
      
});// END PROMISE
return promise;  
}

then your call will look like this: let resolvedData = request(options, callback).then(function(done){console.log(done);});

The only thing i'm not aware is the fact that is kind deprecated method. So maybe it will cause you timeouts. (browser side...)

Also check this source tutorial for alternative ways of HTTP requests, source

Dharman
  • 30,962
  • 25
  • 85
  • 135
George Gotsidis
  • 426
  • 4
  • 15