LauraL
LauraL

Reputation: 11

Sqlite .all() function returns a promise, but I need the database items...?

I'm new to NodeJS, and I'm trying to learn it by building a Shopping cart web app. I'm storing the data in an SQLite database but I can't seem to access it. The .all() method returns a Promise object and I can't figure out how to obtain the items in the database instead.

I followed this tutorial: https://stackabuse.com/a-sqlite-tutorial-with-node-js/ to build a data access object and two models: ItemRepository and CartRepository.

This is the get method in my data access object script:

get(sql, params = []) {
    return new Promise((resolve, reject) => {   
      this.db.get(sql, params, (err, result) => {
        if (err) {
          console.log('Error running sql: ' + sql)
          console.log(err)
          reject(err)
        } else {
          resolve(result)
        }
      }) 
  }

And this is my index.js

router.get('/', function(req, res, next) {
    var dao = new AppDAO('./database.sqlite3');
  var itemRepo = new ItemRepository(dao);
  var cartRepo = new CartRepository(dao);
  items = itemRepo.getAll();
  console.log(items);
  var itemRows = [];
  var rowSize = 3;
  for (var i = 0; i < items.length; i += rowSize){
    itemRows.push(items.slice(i, i+rowSize));
  }
  res.render('shop/index', { title: 'sHOP', items: itemRows })

});

I'm a little lost as for how to get the table's content and not the Promise object.

Upvotes: 1

Views: 1990

Answers (1)

Ganesh Karewad
Ganesh Karewad

Reputation: 1218

I will recommend you to read promises and async/await or bluebird promises. you will need to use then method on promise to get the actual result as below.

router.get('/', function(req, res, next) {
var dao = new AppDAO('./database.sqlite3');
var itemRepo = new ItemRepository(dao);
var cartRepo = new CartRepository(dao);
itemRepo.getAll().then(( items) =>{ 
   console.log(items);
   var itemRows = [];
   var rowSize = 3;
   for (var i = 0; i < items.length; i += rowSize){
    itemRows.push(items.slice(i, i+rowSize));
     }
    res.render('shop/index', { title: 'sHOP', items: itemRows })
   })
});

Upvotes: 1

Related Questions