我目前正在从Wunderground提取天气数据并存储在MongoDB中。我有30个位置来收集数据,但每分钟只能运行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
});
答案 0 :(得分: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);
});
});
}
答案 1 :(得分: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);
})();