4

is there a way I can store a variable in a knex query? Right now I can console.log a query result by doing:

knex.select().table('users').then(function(result) {
    result.forEach(function(value) {
        console.log(value);
    });
});

But I want to store the query result in a variable - something like this:

var query = knex.select().table('users')

so I can pass it onto a template, manipulate it, etc...

One thing I have tried is creating an empty array and pushing each value into the array, but the array returns empty for some reason:

var dataArr = [];
knex.select().table('users').then(function(result) {
    result.forEach(function(value) {
        dataArr.push(value)
    });
});
console.log(dataArr.length) // returns 0
user3674401
  • 55
  • 1
  • 3
  • It's because you're doing an asynchronous call. More information here: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Shanoor Dec 12 '15 at 17:43
  • knex returns a promise, so youll need to use async/await or resolve the promise to store the result of the query in a variable. for eg `var query = await knex.select().table('users') ` – Shivani patel Nov 23 '20 at 10:58

2 Answers2

2

As @ShanShan mentioned, your knex query is run asynchronously, so your call to console.log is being executed before the query results are returned.

You will need to process/use the results after they are passed to then:

return knex('users') // select * from "users"
  .then(function (users) {
    return processUsers(users)
  })
  .then(function (processed) {
    // do something with processed users
  })
thebearingedge
  • 671
  • 5
  • 10
-2

Try to put the console inside the last closing brackets, you will be able to print the length of the array in the console.

09kjs
  • 1