繁体   English   中英

如何在外部访问局部变量

[英]How to access Local variables outside

我有一段代码需要执行以下操作:

  1. 对于数组中的每个Sensor对象,请首先获取模板ID。
  2. 搜索模板模式数据库,获取对应的模板ID的邮政编码。
  3. 从邮政编码生成URI
  4. 进行requestAPI调用
  5. 获取API的输出,并将其存储在该传感器对象的DB中。

我在第5步中遇到问题,将结果存储在每个SenObject的数据库中。 我猜问题是因为newSensorObjectRes是在test()本地定义的,因此不能在外部使用。 我还能如何存储每个对象的结果?

var arr = [];
function SenObj (id)
{
  this.Objnum = 10;
  this.Template = id;
  this.Type = "AirFlow";
  this.UserID = "Jessi";
}
// To store the results from the AIR API
var sensorResults = new Schema({
  //reqId: {type: Number, required: true, unique: true},
  //sensorId: {type: Number},
  SenObj: {type: Number},
  status: {type: String, default: 'Undefined'}
})
var SensorObjectRes = connUserSensors.model('SensorObjectRes', sensorResults)

//API:To create Sensor Objects when user requests for template
// When user makes a request to create a new Template,we get the tempate ID he has requested.
// We use the ID to create a Sensor Object.We might need the request id too here ??
// The array arr[] holds all the sensor obects..

app.get('/ProvisionTemplate/:id', function (req, res) {
  var id = req.params.id;
  console.log("Server recieved a GET /ProvisionTemplate/" + id + " request");
  Template.findOne({templateId: parseInt(id)},function (err, data) {
    if (err) return console.error(err);
    console.log(data);
    res.json(data);
    // Create an Object here
    var user1 = new SenObj(id);
    console.log(user1.UserID);
    arr.push(user1);
  });
});
console.log("The array objects are :");
for (i = 0; i < arr.length; i++)
{
  console.log(arr[i]);
}
var output = ""
function test()
{
  var zip = "";
  console.log("Interval reached");
  for (i = 0; i < arr.length; i++)
  {
    // For each Sensor objects in the array, get the Template ID first.
    // Search the Template Schema DB, get the zipcode of the corresponsing Template ID got.
    // From the zipcode, generate the URI
    // Make the requestAPI call
    // Get the output of the API and store it in the DB for that sensor object.
    console.log(arr[i]);
    console.log(arr[i].Template);
    var tem = arr[i].Template;
    Template.findOne({templateId: tem},function (err, data)
    {
      if (err) return console.error(err);
      console.log(data.zipcode);
      zip = data.zipcode;
      var uri_1 = "http://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=";
      var uri_2 = "&distance=25&API_KEY=1035C2AC-CDB8-4540-97E4-0E8D82BA335A";
      var url = uri_1 + zip + uri_2;
      console.log(url);
      requestApi(url, function (error, response, body)
      {
        if (!error && response.statusCode == 200)
        {
          console.log(body);
          //console.log(arr[i])
          var newSensorObjectRes = new SensorObjectRes({"SenObj": 1 ,"status": body});
          newSensorObjectRes.save(function (err, data)
          {
            if (err)  return console.log("error updating");
              console.log(data);

          })
        }
      })

    });
  }
}
var interval = setInterval(test, 10000);


newSensorObjectRes.find(function (err, data)
{
  if (err)
  {
    console.log("Could not find EC2Server db");
    return;
  }
  console.log(data)
}) 

我相信问题出在测试功能中有一个for循环。 您可能会在收到响应之前发出所有模板请求。 尝试改用递归。 这将确保您的请求以有序的方式提出。 像这样...

function test(i)
{
  if(i == arr.length){
    console.log("done");
    return;
  }
  var zip = "";
  console.log("Interval reached");
  console.log(arr[i]);
  console.log(arr[i].Template);
  var tem = arr[i].Template;
  Template.findOne({templateId: tem},function (err, data)
  {
    if (err) return console.error(err);
    console.log(data.zipcode);
    zip = data.zipcode;
    var uri_1 = "http://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=";
    var uri_2 = "&distance=25&API_KEY=1035C2AC-CDB8-4540-97E4-0E8D82BA335A";
    var url = uri_1 + zip + uri_2;
    console.log(url);
    requestApi(url, function (error, response, body)
    {
      if (!error && response.statusCode == 200)
      {
        console.log(body);
        var newSensorObjectRes = new SensorObjectRes({"SenObj": 1 ,"status": body});
        newSensorObjectRes.save(function (err, data)
        {
          if (err)  return console.log("error updating");
            console.log(data);
            test(i+1);
        })
      }
    })
  });
}
test(0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM