0

Apologies as I'm a bit of a beginner, but am trying to put the get request in variable within a function so that I can call it in another function and have it return the JSON.

function getRequest (url, response) {
var response = request.get({
            url: url,
            json: true,
            headers: {'User-Agent': 'request'}
          }, (err, res, data) => {
            if (err) {
              console.log('Error:', err);
            } else if (res.statusCode !== 200) {
              console.log('Status:', res.statusCode);
            } else {
              console.log(data);
            }
    });
}

Then I have var result = getRequest(urlPlaylist); and have it return the JSON from the function. Can someone help me figure out how to structure that callback? Thank you!

Chris Y
  • 121
  • 2
  • 12
  • See the [accepted answer](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) to the question that yours has been marked a duplicate of. It covers all the various options for returning an asynchronously retrieved value. A variant of this question is asked multiple times a day here since it's one of those things all people who are new to network programming in Javascript have to learn. – jfriend00 Mar 03 '18 at 00:02

1 Answers1

1

The request is async, so you can't just return it. Try something like this, where you pass a callback to be called when the json (data) is ready.

function getRequest (url, cb) {
  request.get({
    url: url,
    json: true,
    headers: {'User-Agent': 'request'}
  }, (err, res, data) => {
    if (err) {
      console.log('Error:', err);
    } else if (res.statusCode !== 200) {
      console.log('Status:', res.statusCode);
    } else {
      cb(data);
    }
  });
}

getRequest(urlPlaylist, function (json) {
  console.log(json);
});
jens
  • 2,075
  • 10
  • 15