[英]Accessing a variable inside a Factory's callback function outside of it in angular
[英]Accessing a function variable from a called function's callback
這是我的下面的代碼,除了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');
}
});
由於請求是異步的,因此它將在您返回return_info
之后執行。 因此,您需要提供該函數的回調,如下所示
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);
});
編輯-與上下文
如果要開始使用node.js,則需要考慮回調方法,下面是有關應如何做的示例。
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');
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.