knex select result return to a variable

拟墨画扇 提交于 2019-12-11 17:25:40

问题


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.



来源:https://stackoverflow.com/questions/48558183/knex-select-result-return-to-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!