0

It seems as if my code is executing out of order...

Here is my code:

console.log("Function Call - " + profAvailable("Plumber"));
function profAvailable(occ) {
    var result = false;
    var reqGet = http.get(optionsget, function(res) {
        res.on('data', function(d) {
            //parsing the data to JSON format
            var parsedShit = JSON.parse(d);
            providers = parsedShit.Providers;//Getting a list of all the providers
            console.log("Provider Length: " + providers.length);
            for (var i = 0; i < providers.length; i++) {
                if (providers[i].Occupation.localeCompare(occ) == 0 && providers[i].Status == 0) {
                    result = true;
                }
            }
        });
    });
    reqGet.end();
    console.log("result - " + result);
    return result;
}

My output is this:

result - false
Function Call - false
Provider Length: 4

My code is calling the function, skipping over the http request, returning the method as false, and then entering the http request which is inside the function (as you can see from the print statements in the code, and output). This is my first time working with stuff like this, so I'm not sure why the code is executing in that order, because it seems strange.

Edit** The value returned by the function depends on info I retrieve from the get call, so how do I fix my code to incorporate that?

Lil Shiva
  • 3
  • 2

1 Answers1

0

That's how the program is expected to behave. You need to get versed with asynchronous programming. Ref: http://rowanmanning.com/posts/javascript-for-beginners-async/

Brahma Dev
  • 1,955
  • 1
  • 12
  • 18
  • Thanks for the link, that was a good brief explanation of why my code is executing the way it is. However, the value my function returns depends on information I retrieve from my GET call, so is there any way around this? – Lil Shiva Sep 10 '17 at 22:44