0

I am making an Http request for some website and that is giving some response

var noOfPages;

const https = require('https');

https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data).explanation);
    data = JSON.parse(data);
    noOfPages = data.no_of_pages;
  });

})

i am able to use it inside closure but cant access that variable outside of this block. can anyone help me with it?

Ankit Baid
  • 71
  • 3
  • 8

1 Answers1

0

This is a bit backwards because youll have no idea when noOfPages is populated.

Why not but the code that relies on noOfPages at the assignment line? ie: change noOfPages = data.no_of_pages; to something that uses data.no_of_pages

Loufs
  • 1,596
  • 1
  • 14
  • 22
  • i have to use the noOfPages variable because based on that JSON response i have to use it in for loop and make another page request passing inside the url. this is not the url. i am using some other url and want to pass value inside that url using string interpolation and that will make a link and based on that it will make request using url – Ankit Baid Nov 24 '17 at 17:37
  • right, you have to do all that when `data.no_of_pages` has a value. That is the point of callbacks. If you tried to move this to the global scope of `noOfPages` you'll have no idea of when `noOfPages` has been populated. – Loufs Nov 24 '17 at 17:40