Search code examples
javascriptnode.jselectronknex.js

Pass to a Variable a query result of knex


I'm trying to attribute the result of a select query with Knexjs to a variable. My code is this:

function getAllCategories() {
let categories;
categories = database.from("categories").select("category").then(function (rows) {
    for (let row of rows) {
        console.log(row)
    }
    });
console.log(categories)

}

When i call the function: .then write on terminal the array of objects like this:

{ category: 'Pasticceria' }
{ category: 'Salati' }
...

Instead if i console.log(categories); on terminal print this:

    Promise [Object] {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined
}

How can I attribute to a variable to be able to cycle it? Many thanks to all for help, I have been banging my head for several days.


Solution

  • getAllCategories returns a promise, which is what you are seeing when you call the function. The easiest thing to do would be to wrap whatever code calls getAllCategories in an async function, then await the value of getAllCategories. I assume that you want getAllCategories to return the categories, so it might look something like this:

    async function wrapper() { 
      async function getAllCategories() {
        return database.from("categories").select("category")
      };
      const categories = await getAllCategories() 
      // do whatever you want to do with categories
     }

    You can read about async/await syntax here