Skip to content
Advertisement

Can someone clarify what is happening in this part of the code?

So I have part of code like this

ruter.get('/', async function (_, res) {
const [categories, items] = (await Promise.all([
    db.query('SELECT * FROM categories'),
    db.query('SELECT * FROM inventory'),
])).map(result => result.rows);

for (const category of categories) {
    category.items = items.filter(item => (item.categoryid === category.id));
}

I have database where I have table-categories and table-items categories table and items look like this:

enter image description here

enter image description here

What I don’t understand is what happens with categories and inventory in this part of code ->

   db.query('SELECT * FROM categories'),
    db.query('SELECT * FROM inventory'),
])).map(result => result.rows);

Do they get joined? Also in this part

category.items = items.filter(item => (item.categoryid === category.id));

what item means here, there is no column named item in items table?

thank you!

Advertisement

Answer

This

const [categories, items] = (await Promise.all([
    db.query('SELECT * FROM categories'),
    db.query('SELECT * FROM inventory'),
])).map(result => result.rows);
  • makes two queries – one from categories, one from inventory
  • in parallel, with Promise.all
  • then takes the rows property from each query result and puts those into the categories and items variables.

They don’t get joined – they’re two entirely independent queries and get put into separate categories and items variables.

what item means here

With

items.filter(item =>

items is the result of the query SELECT * FROM inventoryitem is a single row from that query.

1 People found this is helpful
Advertisement