1

** Newbie to Javascript. Please help **

I am writing a simple 'for' loop in Javascript and I am not getting the expected output. Request help.

for (i = 1; i < 5; i++) {
  console.log(i + ": " + makeARestCall(options));
}

function makeARestCall(options) {
  request(options, function(error, response, body) {
    if (error) throw new Error(error);
    let test = getCount(body);
    console.log("Hello: " + test);
  });
}

function getCount(body) {
  const data = JSON.parse(body.toString()).test.all;
  return data;
}

makeARestCall(options) - function makes a Rest call to a service and gets some data. getCount(body) - returns a value from the JSON received from makeARestCall function.

How am I executing: Writing a Mocha Test using Javascript.

What is the current output:

1: undefined
2: undefined
3: undefined
4: undefined
Hello: 35
Hello: 35
Hello: 35
Hello: 35

What am I expecting?

1: Hello: 35
2: Hello: 35
3: Hello: 35
4: Hello: 35

It appears 'for' loop runs so quickly and makeARestcall takes time to execute because it takes couple of seconds for execution. Please help on how I can get the desired output.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Mike
  • 899
  • 9
  • 27
  • 45

1 Answers1

4

request runs asynchronously, not synchronously, and makeARestCall does not return anything currently. You should probably have makeARestCall return a promise which is then consumed in the for loop:

for (let i = 1; i < 5; i++) {
  makeARestCall(options)
    .then(responseStr => console.log(i + ': ' + responseStr));
}

function makeARestCall(options) {
  return new Promise((resolve, reject) => {
    request(options, function(error, response, body) {
      if (error) reject(error);
      let test = getCount(body);
      resolve("Hello: " + test);
    });
  });
}

Make sure to use let i and not var or no declaration at all, else i will be hoisted to the outer block and will have the same value (5) once all the requests come back. (Try to avoid implicitly creating global variables)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks a lot. Promise is a new concept for me. This greatly helps and I will read more on promise.. – Mike May 07 '18 at 02:45