Saturday 18 August 2018

Variable scope within app.get

Henlo,I am having some trouble with variable scoping within app.get code. I am declaring an array (ARRAY) at the top of the code. I am then looping through another array, and making a request for each item and pushing it to ARRAY. However, if I send an app.get response passing my ARRAY, it is empty. It only contains values within the getData code block.Since I am declaring the array at the top of the parent block, shouldn't the function blocks within th forEach loop and the getData block have access and be able to manipulate it?const app = express(); const getData = require("request"); // .... unrelated code here app.get("/", function (request,response){ var searchTerms = ["One","Two","Three"]; var ARRAY = [""]; searchTerms.forEach(function(item){ let reqURL = "APIURL" + item; getData(reqURL,function(error,res,body){ if(!error && res.statusCode==200){ ARRAY.push(JSON.parse(body)); } }); // END OF GETDATA }); // END OF FOR EACH LOOP response.render("main.ejs",{ARRAY:ARRAY}); });

Submitted August 18, 2018 at 09:39PM by Nate_Dev

No comments:

Post a Comment