I am currently having an issue with figuring out how to wait for the request to finish before returning any data. I do not believe I can do this with a Callback and I have not been able to figure out a good way of using the EventEmitter to do it. The reason I cannot use a callback is because my flow currently works like this.
Request comes into server > Generate XML > Contact remote API for details to finish generating XML > Finish Generating XML > Return request to client
The code I currently have looks very similar to the code included below.
Web Server:
var xml = require('./XMLGenerator');
response.writeHead(200, {'Content-Type': 'text/xml'});
response.write(xml.generateXML());
response.end();
XML Generator:
function generateXML(){
// Code to generate XML
var API = require('./API');
var response = API.getItems("5");
for(var i = 1; i <= response.length; i++)
{
// more code to generate further XML using the API response
}
// Finish generating and return the XML
}
API Grabber:
function getItems(sort_by, amount) {
var request = require("request")
var url = "https://url.com/api/get_items.json?amount=" + amount;
request({
url: url,
json: true
}, function (error, response, body) {
console.log('we got here!');
if (!error && response.statusCode === 200) {
var items = body.data.items;
console.log(items);
return items;
} else {
console.log("Error connecting to the API: " + url);
return;
}
})
}
When running the code and testing directly it returns "undefined" meaning that the request has not been made yet. I just need to know a way to make the XML generator wait for the request to finish before continuing on with the generation. (there may be minor errors in the psudeo code I typed up as it is not an exact copy paste from the source, it does however work in this flow)
Am I just using bad practices, or is this the correct way that I should be attempting this?
EDIT: The problem is not loading the module/API file, that loads perfectly fine. The problem is that the request takes about 2 seconds to complete, and that node moves on before the request completes.