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
}
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 thereturn dataArr
returns the value to the caller's.then()
promise clause.Call the function via:
The
result
variable will be set when theaPromise
resolves.Calling the function using
var aPromise
will cause program execution to continue before the Promise is fulfilled and theresult
is set, which may not be what you want. So you can useawait
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.