1

I need to get knex select query result to a variable.

function getUserPlanDetailsWithOutCb(user_id) {
 var dataArr =[];
 knex('user_plans').select('*').where({ 'user_id': user_id }).then(function(result) {
     result.forEach(function(value) {
        dataArr.push(value)
     });
 //return dataArr;
 });
 return dataArr;
}

 var result = getUserPlanDetailsWithOutCb(12);

I have tried return value outside and inside of the call back in knex. For above code i got the result as [ ] For second one (return inside callback) i got the result as

{
   "isFulfilled": false,
   "isRejected": false
}
reshma
  • 672
  • 8
  • 24
  • What is the question? – Waleed Iqbal Feb 01 '18 at 08:24
  • i need to get the result of this query to a variable. Like, var result = getUserPlanDetailsWithOutCb(19); – reshma Feb 01 '18 at 09:12
  • @Pillai It's an asynchronous function, so you have to pass a callback. Or you can use async/await with promises. – Abhyudit Jain Feb 01 '18 at 09:20
  • Have a look at this ... https://stackoverflow.com/questions/34094806/return-from-a-promise-then – Waleed Iqbal Feb 01 '18 at 09:37
  • @WaleedIqbal what i need is to assign result to a variable. I need to use that variable again. – reshma Feb 01 '18 at 10:19
  • @AbhyuditJain **async function getUserPlanDetailsWithOutCb(user_id) { return await knex('user_plans').select('*').where({ 'user_id': user_id}).limit(10); } var payment_data =User.getUserPlanDetailsWithOutCb(user.user_id);** But i got **_Promise { }_** – reshma Feb 01 '18 at 11:42

1 Answers1

5

To get your variable returned using Promises, do the following to the data retrieval function:

And note: The return knex( returns the Promise object to the caller, and the return dataArr returns the value to the caller's .then() promise clause.

function getUserPlanDetailsWithOutCb(user_id) {
  var dataArr =[];
  return knex('user_plans').select('*')
     .where({ 'user_id': user_id })
     .then(function(result) {
         result.forEach(function(value) {
            dataArr.push(value)
         });
         return dataArr;
     });
}

Call the function via:

var result;
var aPromise = getUserPlanDetailsWithOutCb(12)
    .then(function(result) {
        result = value;
    });

The result variable will be set when the aPromise resolves.

Calling the function using var aPromise will cause program execution to continue before the Promise is fulfilled and the result is set, which may not be what you want. So you can use await instead (as @Abhyudit Jain notes), but I haven't done that, so I would mess up the syntax for you if I tried.

Cheers! Gary.

GaryL
  • 1,385
  • 8
  • 11
  • when only returning one column, i believe this works as well: ```.select('oneColumn') .where({ 'user_id': user_id }) .then( val => { return val; } ) ``` - opinions? – edwardsmarkf Feb 02 '22 at 21:37