这是我下面的代码,除了 return_info 没有设置之外,它都可以正常工作。是否可以从请求函数调用的回调中访问父 return_info 变量?
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;
}
}
编辑:供进一步参考,这是调用它的代码。
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');
}
});