** 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.