This is my code below, it's all working with the exception of return_info not getting setup. Is it possible to access the parent return_info variable from within the callback that is called by the request function?
module.exports = {
fetch_template_by_id : function(id) {
var request = require('request');
var return_info = {}; //TO BE MODIFIED
request('http://localhost:5000/templates/v1/template/' + id, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Success - Error = " + error + " | Response = " + response + " | Body = " + body);
return_info.body = body; // Should Modify the top
return_info.json = JSON.parse(body); // Should Modify the top
return_info.success = true; // Should Modify the top
} else {
console.error("There was an error requesting template ID=" + id)
return_info.error = error; // Should Modify the top
return_info.response = response; // Should Modify the top
return_info.success = false; // Should Modify the top
}
});
return return_info;
}
}
EDIT: For Further reference this is the code that calls it.
app.get('/form', function (req, res) {
var template_helper = require('../services/template-helper');
var template = template_helper.fetch_template_by_id("BirthRecord");
console.log(template);
if (template.success === true) {
res.render('form', {"template": template.json });
} else {
res.render('index');
}
});
As request is asynchronous, it will execute after you have returned return_info
. So, you need to provide a callback to the function as show below
module.exports = {
fetch_template_by_id : function(id, cb) {
var request = require('request');
var return_info = {}; //TO BE MODIFIED
request('http://localhost:5000/templates/v1/template/' + id, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Success - Error = " + error + " | Response = " + response + " | Body = " + body);
return_info.body = body; // Should Modify the top
return_info.json = JSON.parse(body); // Should Modify the top
return_info.success = true; // Should Modify the top
} else {
console.error("There was an error requesting template ID=" + id)
return_info.error = error; // Should Modify the top
return_info.response = response; // Should Modify the top
return_info.success = false; // Should Modify the top
}
cb(return_info);
});
}
}
fetch_template_by_id('awesome', function (info) {
console.log(info);
});
EDIT - With the context
You need to think along the callback ways if you want to start working with node.js, Below is the example on how you should do it.
app.get('/form', function (req, res) {
var template_helper = require('../services/template-helper');
template_helper.fetch_template_by_id("BirthRecord", function (template) {
console.log(template);
if (template.success === true) {
res.render('form', {"template": template.json });
} else {
res.render('index');
}
});
});