0

I am new to JavaScript and am attempting a do/while statement below

let increment = 0
do {
  const https = require('https');
  https.get('https://www.reddit.com/r/worldnews/new/.json?limit=5', (resp) => {
    let data = '';
    resp.on('data', (chunk) => {
      data += chunk;
    });
    resp.on('end', () => {
      let title = (JSON.parse(data).data.children[increment].data.title);
      console.log(increment + ', ' + title)
    });
  }).on('error', (err) => {
    console.log('Error: ' + err.message);
  });
  increment++;
} while (increment < 2);

My current result is:

2, post title
2, post title

I would expect a console.log of:

1, post title
2, post title

Any help would be appreciated

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Since `increment` is provided outside the loop, and API calls are asynchronous, your variable will max out before the calls finish. – Mr. Polywhirl Nov 11 '22 at 17:48

0 Answers0