【发布时间】:2013-12-03 14:36:03
【问题描述】:
我是 node.js 的新手。我想要达到的目标如下:
- 连接到我的 postgresql 数据库并获取地点信息(id、坐标)。
- 调用天气API,使用上一步获得的坐标获取该地点的信息。
- 在数据库中插入返回的 json。我得到 8 个每小时的对象,每 3 小时(0、3、6、9、12、15、18、21)有天气信息。我需要遍历这些对象并将它们存储在数据库中的 8 条记录中。
我写了以下代码:
app.get('/getapi', function(req, res){
var json_bbdd;
//------------ BBDD CONNECTION----------------
var pg = require('pg');
var conString = "postgres://postgres:postgres2@localhost/places";
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
console.log('could not connect to postgres');
}
client.query('SELECT * from places where id=3276', function(err, result) {
if(err) {
console.log('error running query');
}
json_bbdd=result.rows[0];
var coords = JSON.parse(json_bbdd.json).coordinates;
var id = json_bbdd.id;
var input = {
query: coords[1] + ',' + coords[0] ,
format: 'JSON',
fx: '',
callback: 'MarineWeatherCallback'
};
var url = _PremiumApiBaseURL + "marine.ashx?q=" + input.query + "&format=" + input.format + "&fx=" + input.fx + "&key=" + _PremiumApiKey + "&tide=yes";
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (json) {
var date= json.data.weather[0].date;
for (var i=0; i < 8; i++){
var hourly = json.data.weather[0].hourly[i];
var time= hourly.time;
client.query('INSERT into parte (id, date, time) VALUES($1, $2, $3)', [id, date, time],
function(err, result) {
if (err) {
console.log(err);
} else {
console.log('row inserted: ' + id + ' ' + time);
}
});
} // FOR
},
error: function (e) {
console.log(e.message);
}
});
client.end();
});
});
});
第 1 步和第 2 步完美执行。另一方面,第三步什么都不做,甚至没有抛出错误。
我在这篇文章中读到:node-postgres will not insert data, but doesn't throw errors either 使用异步模块可能会有所帮助,但我不知道如何重写代码。我需要一些帮助。
问候, 飞行员
【问题讨论】:
标签: node.js postgresql asynchronous insert