1

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

1 回答 1

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');
    }
  });
});
于 2012-07-13T16:36:15.970 回答