1

Everything is working fine but empty array is returned so there's no output which can be noted when 2 outputs before 1. Can someone tell me what am I missing here? I tried making it work but couldn't so finally posting here.

'use strict';
var https = require('https');

async function main() {
  var a = "hey";
  var result = await fetchData(a);
  result = result.join(" ");
  console.log(result);
}

async function fetchData(substr) {
  let pageNum = 1;
  var sortArray = [];
  let url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + pageNum;
  try {
    https.get(url, (res) => {
      res.setEncoding('utf8');
      res.on('data', function(body) {
        let dataRec = JSON.parse(body);
        let movies = dataRec.data;
        let totPages = dataRec.total_pages;
        movies.map((a) => {
          sortArray.push(a.Title);
          console.log("1");
        });
        for (let i = 2; i <= totPages; i++) {
          let newPage = i;
          let url1 = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + newPage;
          https.get(url1, (res) => {
            res.setEncoding('utf8');
            res.on('data', function(body) {
              let newData = JSON.parse(body);
              let newMovies = newData.data;
              for (let i = 0; i < newMovies.length; i++) {
                sortArray.push(newMovies[i].Title);
              }

            });
          });
        }

      });
    });
  } catch (e) {
    console.log(e);
  }
  console.log("2")
  return sortArray;
}

main();
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Nick Parsons Mar 21 '21 at 05:17
  • Also, unrelated to your issues, but worth looking at: [Is performing a mapping operation without using returned value an antipattern?](https://stackoverflow.com/q/56903693) – Nick Parsons Mar 21 '21 at 05:17

0 Answers0