-3

The get_customers() function queries the database for the playlists records and logs to the console each row. But the data array is returned as an empty list array. How to return the data from the get_playlists function?

...result undefined
const sqlite3 = require('sqlite3').verbose();

let db = new sqlite3.Database('mydb.db', (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the database.');
});



function get_playlists(db){
    let sql = `SELECT DISTINCT Name name FROM playlists
               ORDER BY name`;

    let data = []
    db.all(sql, [], (err, rows) => {
      if (err) {
        throw err;
      }
      rows.forEach((row) => {
        console.log(row.name);
        data.push(row.name);
      });
      return data
    });
}

result = get_playlists(db)
console.log('...result', result);
db.close();
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • 1
    console.log is running before db.all is finished. Wrapp the contents of get_playlists in a promise and resolve it with `data` – Gavin Sep 16 '19 at 18:19

1 Answers1

0

Wrap the content of get_playlists function in Promise and resolve with rows:

const sqlite3 = require('sqlite3').verbose();

let db = new sqlite3.Database('mydb.db', (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the database.');
});


function get_playlists(db) {
    return new Promise( (resolve, reject) => {
        let sql = `SELECT DISTINCT Name name FROM playlists ORDER BY name`;

        db.all(sql, [], (err, rows) => {
            if (err) { throw err; }
            resolve(rows);
        });
    })
}


let rows ; 
get_playlists(db).then( res => {
    rows = res;
    rows.forEach( (row) => { console.log('row:', row) } );

});

db.close();
alphanumeric
  • 17,967
  • 64
  • 244
  • 392