AxleCat
AxleCat

Reputation: 57

NodeJS and Express - Exports function skips over SQLite3 DB query

Trying to link a function in a separate JS file to my index, but part of the function is skipped over, returns to the index.js app.post method, and the finally returns back to the db query it skips over in the other JS file.

sales.js =

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

const db = new sqlite3.Database('./database/stock.db', (err) => {
    if (err) return console.error(err.message)
    console.log('Connected to the "stock.db" SQlite database.')
})

module.exports = {

sale: function(formData, cartlist) {
    const item = parseInt(formData, 10)
    console.log(item)
    const sql = "SELECT name, price FROM products WHERE barcode_id = " + item + ";"
    console.log(sql)
    console.log("test1")
    db.all(sql, (err, data) => {
        if(err) console.error(err.message)
        console.log("test2")
        cartlist = cartlist.concat(data)
        console.log(cartlist)
    })
    console.log("test3")
    return cartlist
}
}

index.js (relevant parts) =

const sales = require('./sale.js')

. . . .

var cartlist = []

app.post('/sales', async(req, res) => {
    const formData = String(req.body.Barcode)
    cartlist = await sales.sale(formData, cartlist)
    console.log(cartlist)
    res.render('cart', {purchases: cartlist})
})

. . .

I have the tests there to show order and test1 gets logged first, followed by test3, and then back to test2, showing it jumps out, then back in again. Not familiar with SO formatting or Node.js so apologies in advance. I imagine this somewhat involves callback functions, but I have yet to fully understand how they work.

Upvotes: 0

Views: 199

Answers (2)

ViqMontana
ViqMontana

Reputation: 5688

I believe db.all is an async method, therefore you need to await the method if you want to pause execution. Try this:

await db.all(sql, (err, data) => {
    if(err) console.error(err.message)
    console.log("test2")
    cartlist = cartlist.concat(data)
    console.log(cartlist)
})

Upvotes: 0

enapupe
enapupe

Reputation: 17019

You are returning an empty array on sale function. You need to understand the async nature of JS and how event loop works.

To make your piece of code work you usually make use of async/promise:

sale = function(formData, cartlist) {
    return new Promise((resolve) => {
      const item = parseInt(formData, 10)
      const sql = 'SELECT name, price FROM products WHERE barcode_id = ' + item + ';'
      db.all(sql, (err, data) => {
        if (err) console.error(err.message)
        console.log('test2')
        cartlist = cartlist.concat(data)
        resolve(cartlist)
      })
    })
  }

Upvotes: 1

Related Questions