knex select result return to a variable

2019-08-19 13:53发布

问题:

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
}

回答1:

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.