0

我目前正在从 Wunderground 提取天气数据并存储在 MongoDB 中。我有三十个位置可以收集数据,但每分钟只能运行 10 个查询,所以我试图设置一个“计时器”,每 10 秒左右查询一次数组中的每个邮政编码。

现在我的代码可以成功收集数据并将其写入 Mongo,所以这不是问题。问题在于设置每个 api 调用之间的延迟。由于我对 javascript 还很陌生,甚至对异步处理也很陌生,这给我带来了一些麻烦。我试过使用 setInterval() 没有太大成功。

MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err,db) {
var zip = ["zip1","zip2","zip3","zip4","zip5","zip6","zip7"] ;
for(var i = 0; i<zip.length; i++) {

  // Define the Wunderground method.
  var method = "/api/" + apiKey + "/conditions/q/" + zip[i] + ".json";

  // Define the HTTP post properties.
  var options = {
    host: 'api.wunderground.com',
    path: method,
    method: 'GET',
    port: 80
  };

  // Create the HTTP POST.
  var request = http.request(options, function (response) {
    var str = '';

    // Create the listener for data being returned.
    response.on('data', function (chunk) {
      str += chunk;
    });

  // Create the listener for the end of the POST.
  // Send data to MongoDB

    response.on('end', function (){
      var myObject = JSON.parse(str);

            var location = myObject.current_observation.display_location.full
            db.collection('weathercollection').save(myObject, function(err, records) {
              console.log(location);
            });       
    db.close;
    });             // close response.on
  });               // close var request
  request.end();    // Close the HTTP connection.
};                  //close for loop
});
4

2 回答 2

2

我建议类似:

MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) {
    var zips = ["zip1", "zip2", "zip3", "zip4", "zip5", "zip6", "zip7"];
    getWeather(zips, zips[0], db);
});

function getWeather(zips, zip, db) {
    var options = {
        host   : 'api.wunderground.com',
        path   : "/api/" + apiKey + "/conditions/q/" + zip + ".json",
        method : 'GET',
        port   : 80
    };

    var request = http.request(options, function (response) {
        var str = '';

        response.on('data', function (chunk) {
            str += chunk; // why get chucked data if you need it all ?
        });

        response.on('end', function () {
            var myObject = JSON.parse(str);

            var location = myObject.current_observation.display_location.full
            db.collection('weathercollection').save(myObject, function (err, records) {
                console.log(location);
            });
            db.close;
            request.end();
            var next_zip = zips.indexOf(zip) == zips.length ? 0 : zips.indexOf(zip) + 1;
            setTimeout(function () {
                getWeather(zips, next_zip, db);
            }, 10000);
        });
    });
}
于 2013-11-14T18:56:40.233 回答
1

一种方法是使用 setTimeout 而不是for循环:

当前的:

for(var i = 0; i<zip.length; i++) {
    //Make request...
}

新的:

var i = 0;
(function loopFn() {
  // Make request...
  i++;
  if (i < zip.length) setTimeout(loopFn, 10000);
})();
于 2013-11-14T18:54:44.397 回答