【问题标题】:Node.js Async | insert into postgresql database results from apiNode.js 异步 |从 api 插入 postgresql 数据库结果
【发布时间】:2013-12-03 14:36:03
【问题描述】:

我是 node.js 的新手。我想要达到的目标如下:

  1. 连接到我的 postgresql 数据库并获取地点信息(id、坐标)。
  2. 调用天气API,使用上一步获得的坐标获取该地点的信息。
  3. 在数据库中插入返回的 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


    【解决方案1】:

    好的,现在又遇到了另一个问题...我怀疑是否要创建一个新帖子,但我认为这可能与之前的帖子有关。

    目的是从数据库中读取一个位置而不是三个位置,并为每个位置执行与以前相同的过程。 代码如下(有ivoszz提出的修改):

    app.get('/getapi', function(req, res, next){  
    //------------ BBDD CONNECTION----------------
    
      pg.connect(conString, function(err, client, done) {
        if(err) {
          // example how can you handle errors
          console.error('could not connect to postgres',err);
          return next(new Error('Database error'));
        }
        client.query('SELECT * from places where id>3274 and id<3278', function(err, result) {
          if(err) {
            console.error('error running query',err);
            done();
            return next(new Error('Database error'));
          }
    
          var first_callback = 0;
          for (var y=0;  y<result.rows.length; y++) {
              var coords = JSON.parse(result.rows[y].json).coordinates;
              var id = result.rows[y].id;
              var input = {
                query: coords[1] + ',' + coords[0] ,
                format: 'JSON',
                fx: ''
              };
    
              var url = _PremiumApiBaseURL + "marine.ashx?q=" + input.query + "&format=" + input.format + "&fx=" + input.fx + "&key=" + _PremiumApiKey;
    
              request(url, function(err, resp, body) {
                body = JSON.parse(body);
                if (!err && resp.statusCode == 200) {
    
                  var date = body.data.weather[0].date;
                  var callbacks = 0;
    
                  for (var i=0; i < 8; i++) {
    
    
                    var hourly = body.data.weather[0].hourly[i];
    
                    client.query(
                      'INSERT into parte (id, date, time) VALUES($1, $2, $3)',
                      [id, date, hourly.time], 
                      function(err, result) {
                        if (err) {
                          console.log(err);
                        } else {
                          console.log('row inserted: ' + id + ' iteration ' + i);
                        }
                        callbacks++;
                        if (callbacks === 8) {
                          console.log('All callbacks done!from id '+id);
                          //done();    // done(); is rough equivalent of client.end();
                          //res.send("done");
                        }
                    }); 
    
                  } // FOR
                }
                else { // if the API http request throws an error
                   console.error(err);
                   done();    // done(); is rough equivalent of client.end(); 
                   return next(new Error('Http API error'));
                } 
              }); // REQUEST API URL
    
          first_callback++;
          if (first_callback === result.rows.length-1) {
            console.log('All global callbacks done!');
            done();    // done(); is rough equivalent of client.end();
            res.send("done");
          }} 
        }); // SELECT from pg
      }); // CONNECT to pg
    }); // app.get
    

    我不知道为什么它尝试插入 id=3277 三次而不是插入 id=3275、id=3276 然后 id=3277... 它的作用是:它插入前 8 条记录 ok第一次(id = 3277),但随后它抛出一个错误,说记录已经插入(主键= id,日期,时间),id 3277 ...

    似乎首先执行第一个 FOR 的 3 次迭代,然后执行第二个 FOR 的 3 次迭代,但使用最后一次迭代(位置)的信息。不是很懂。。。

    【讨论】:

      【解决方案2】:

      我没有测试你的sn-p,我只能帮助你解决我认为不好的事情。

      1. 最好不要在节点服务器上使用 jQuery。有一个很棒的库叫做 request 来做远程 http 请求。
      2. 您应该更好地处理数据库错误,因为在您的示例中,您的代码将在数据库错误后继续运行。
      3. 您调用client.end() 为时过早,并且在您尝试将数据插入数据库时​​,连接已关闭。您必须在成功和错误函数的末尾移动client.end(),然后等待所有回调完成。
      4. 我认为使用连接池而不是Client也更好。
      5. 您可以在 PostgreSQL 中使用 JSON 类型来避免在您的代码中序列化/反序列化 JSON 数据。

      这是修改后的示例(未经测试)。我没有在这里替换 jQuery,包括一些小的调整。

      var pg = require('pg'); 
      var conString = "postgres://postgres:postgres2@localhost/places";
      
      app.get('/getapi', function(req, res, next){
      var json_bbdd;  
      //------------ BBDD CONNECTION----------------
      
        pg.connect(conString, function(err, client, done) {
          if(err) {
            // example how can you handle errors
            console.error('could not connect to postgres');
            return next(new Error('Database error'));
          }
          client.query('SELECT * from places where id=3276', function(err, result) {
            if(err) {
              console.error('error running query');
              done();
              return next(new Error('Database error'));
            }
      
            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;
                var callbacks = 0;
      
                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);
                      }
                      callbacks++;
                      if (callbacks === 8) {
                        console.log('All callbacks done!');
                        done();    // done(); is rough equivalent of client.end();
                      }
                  }); 
      
                } // FOR
              },
              error: function (e) {
                 console.error(e.message);
                 done();    // done(); is rough equivalent of client.end(); 
                 return next(new Error('Http error'));
              }
            });
          });
        });
      });
      

      【讨论】:

      • 感谢您的所有提示。您的代码完美运行!我还使用请求模块更改了 http 调用。谢谢!
      猜你喜欢
      • 2013-12-05
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      相关资源
      最近更新 更多