从被调用函数的回调中访问函数变量

时间:2012-07-13 16:32:30

标签: javascript node.js

这是我下面的代码,除了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');
}
});

1 个答案:

答案 0 :(得分:0)

由于请求是异步的,它将在您返回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');
    }
  });
});