Javascript Node.js函数没有';是否刷新id参数(范围问题)?

Javascript Node.js函数没有';是否刷新id参数(范围问题)?,javascript,node.js,parameters,scope,Javascript,Node.js,Parameters,Scope,我是node.js的新手。我正在努力实现以下目标: 连接到我的postgresql数据库并获取三个位置(id、坐标)的信息。对于获得的每个地点,我需要: 调用天气api并使用上一步中获得的坐标获取该地点的信息 在数据库中插入返回的json。我每小时会得到8个对象,每3小时(0,3,6,9,12,15,18,21)会得到一次天气信息。我需要遍历这些对象,然后将它们存储在数据库中的8条记录中 到目前为止,我已经编写了以下代码: function insert_forecast_spot(id, bo

我是node.js的新手。我正在努力实现以下目标:

  • 连接到我的postgresql数据库并获取三个位置(id、坐标)的信息。对于获得的每个地点,我需要:
  • 调用天气api并使用上一步中获得的坐标获取该地点的信息
  • 在数据库中插入返回的json。我每小时会得到8个对象,每3小时(0,3,6,9,12,15,18,21)会得到一次天气信息。我需要遍历这些对象,然后将它们存储在数据库中的8条记录中
  • 到目前为止,我已经编写了以下代码:

    function insert_forecast_spot(id, body, client) {
      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);
                                    }
                                  }   
                                });
        } //for
      } // function
    
    
    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'));
          }
          done();
          var first_callback = 0;
          for (var y=0;  y<result.rows.length; y++) {
              console.log('y'+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) {
    
                      insert_forecast_spot(id,body, client);
                  }
                  else { 
                     console.error(err);
                     done();    // done(); is rough equivalent of client.end();  
                  }
                });
    
          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 
      }); // CONNECT
    }); // app.get
    

    最后一个错误重复16次,因为它尝试再次插入该位置的8条记录两次。

    query
    是异步的。您应该意识到这个相关的Q/A:classic for loop作用域问题出了什么问题。
    y0
    y1
    All global callbacks done!
    GET /getapi 200 40ms - 4b
    y2
    row inserted: 3277 iteration 8
    row inserted: 3277 iteration 8
    row inserted: 3277 iteration 8
    row inserted: 3277 iteration 8
    row inserted: 3277 iteration 8
    row inserted: 3277 iteration 8
    row inserted: 3277 iteration 8
    row inserted: 3277 iteration 8
    All callbacks done!from id 3277
    { [error: duplicate key value violates unique constraint "parte_pkey"]
      name: 'error',
      length: 178,
      severity: 'ERROR',
      code: '23505',
      detail: 'Key (id, date, "time")=(3277, 2013-11-22, 0) already exists.',
      hint: undefined,
      position: undefined,
      internalPosition: undefined,
      internalQuery: undefined,
      where: undefined,
      file: 'nbtinsert.c',
      line: '397',
      routine: '_bt_check_unique' }