0

I am quite new to Javascript so forgive me if I am not seeing something. I am trying to query a SQLite database and obtain float values of a particular column. I then want to add each row's value of that column to an array. Here is what I have so far:

const sqlite3 = require('sqlite3').verbose();
var latitudes = [];
var longitudes = [];
var altitudes = [];

var centerLat = 0;
var centerLon = 0;


let db = new sqlite3.Database('C:/sqlite/gpsdata.db', sqlite3.OPEN_READWRITE, (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the GPS database.');
});

db.each("SELECT * FROM GPSDATA", [], (err, row) => {
    if (err) {
      console.error(err.message);
    }
    
    console.log(parseFloat(row.LATITUDE));
    latitudes.push(parseFloat(row.LATITUDE));
    latitudes.push(5);
  });

console.log(latitudes.length);


db.close((err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Closed the database connection.');
});

The console outputs:

0
Connected to the GPS database.
50.852184
50.852184
50.852184
50.852184
50.852184
50.852184
50.852184
50.852184
50.852184
50.852184
50.852184
50.852184
50.852184
50.852184
50.85218
50.85218
50.85218
50.85218
50.85218
50.85218
Closed the database connection.

As you can see I guess it's querying the database correctly, but pushing these values to the array doesn't seem to work. Even if I push a random value. the size remains 0. I feel like it's not working because I am not in the right scope or something. How can I work around this?

Diyon335
  • 27
  • 9
  • 1
    It works, you're just misunderstanding the order in which this all happens. This is asynchronous. Move your `console.log(latitudes.length);` inside the callback for `db.close` so that it can be executed **after** pushing the data inside the Array – blex Jun 24 '20 at 21:51
  • 1
    In the [documentation](https://github.com/mapbox/node-sqlite3/wiki/API#statementeachparam--callback-complete) there is also a second `complete` callback specified for the `each` statement. "After all row callbacks were called, the completion callback will be called if present." Same basic concept as what @blex suggests. – David784 Jun 24 '20 at 21:55
  • @blex thank you very much – Diyon335 Jun 24 '20 at 22:30

0 Answers0