我刚刚开始学习 Node.js,我正在尝试一个同时查询 Factual API 和 Google maps API 的项目。我一直在将来自几个不同来源的代码放在一起,它正在变成一团糟的回调。此外,它目前使用 for 循环,这意味着循环中的异步 API 调用永远不会运行。如果有人能帮助我重构这段代码并告诉我如何让 HTTP 请求在循环中运行,我将不胜感激。
这是我当前的代码,其中出现错误“TypeError:无法读取未定义的属性'腿'”:
var auth = require('./auth');
var Factual = require('./node_modules/factual-api');
var factual = new Factual(auth.key, auth.secret);
var path = require('path');
var express = require('express');
app = express();
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
});
var http = require("http");
app.get('/', function(req, res) {
var placedata = "<link rel='stylesheet' type='text/css' href='default.css' /> <table>";
factual.get('/t/restaurants-gb', {
limit: 50,
sort: "$distance:asc",
geo: {
"$circle": {
"$center": [req.query.lat, req.query.lng],
"$meters": 15000
}
}
}, function(error, result) {
for (var i = 0; i < result.data.length; i++) {
var d = new Date();
var seconds = (d.getTime() / 1000).toFixed(0);
url = "http://maps.googleapis.com/maps/api/directions/json?mode=transit&origin=" + req.query.lat + "," + req.query.lng + "&destination=" + result.data[i].latitude + "," + result.data[i].longitude + "&sensor=false&departure_time=" + seconds;
var request = http.get(url, function(response) {
var buffer = "",
data, route;
response.on("data", function(chunk) {
console.log(buffer);
buffer += chunk;
});
response.on("end", function(err) {
data = JSON.parse(buffer);
route = data.routes[0];
console.log("Time: " + route.legs[0].duration.text);
placedata += "<tr><th align='left'>" + result.data[i].name + "</th><td>" + result.data[i].address + "</td><td>" + result.data[i].tel + "</td><td>" + result.data[i].$distance + " Metres" + "</td></tr>";
});
});
}
placedata += "</table>";
res.send(placedata);
console.log(">> Home");
});
});
app.listen(process.env.PORT, process.env.IP, function() {
console.log('Server is running');
});