Thursday, 13 April 2017

Having trouble updating global variable in Javascript

I'm having trouble updating a global variable in my Node app. Can someone look at my code and let me know what's going wrong? I've defined a dowhile loop to run as long as my HTTP response object does not have "next" defined. Inside the loop, things are running as expected and new_json.next is defined, but the while condition is returning an error because new_json.next is undefined there. I'm a little new at Javascript, so somehow my variable scope is off, but I can't figure out how to do things correctly based on other questions.

    function make_pagination_request(json, create_response_data) {    


        var new_json={};
        do {    

            var options = {
                 host: slug + '.nationbuilder.com',  //should be replaced to be site-agnostic
                 path: json.next,
                 method: "GET",
                 json: true,
                 headers: {
                     "content-type": "application/json",
                     "accept": "application/json"
                 },
            }    

            var req = https.get(options, req_callback);    


            function req_callback(response) {
                response.on('data', function(chunk) {
                    str += chunk;
                });    

                response.on('end', function(new_json) {    

                    new_json=JSON.parse(str);
                    new_results = new_json.results
                    results= results.concat(new_results);
                    console.log("combinedlength: " + results.length)
                    console.log(new_json.next);


                });
            }
        } while (new_json.next.includes("api"));



via Peter Breen

No comments:

Post a Comment