使用回调函数的Javascript异步方法问题

时间:2018-04-26 23:57:36

标签: javascript asynchronous callback

拥有以下名为库:

var rd = require('redis.dump')

用于函数查询数据库并进行一些处理然后返回

function query(type, row, column){
  var output = []
  ...
  rd({
      filter: ...
      port  : ...
      format:  ...
      },
      function(err, result){
       [where the processing of result begins]
       ...
       output = [processed result]
       ...
      }
     });
  return output;
  }

如何在异步中等待直到rd完成然后返回输出? 我尝试了以下操作并失败了:

function query(type, row, column){
  var output = []
  ...
  rd({
      filter: ...
      port  : ...
      format:  ...
      },
      async function convert(err, result){
       [where the processing of result begins]
       ...
       output = [processed result]
       ...
      }
     });
  rd.convert.then(return output);
  }   

带有TypeError:

TypeError: Cannot read property 'then' of undefined

提前致谢

1 个答案:

答案 0 :(得分:0)

// replace your code into this 
function query(type, row, column,cb){
  var output = []
  ...
  rd({
      filter: ...
      port  : ...
      format:  ...
      },
      function(err, result){
       [where the processing of result begins]
       ...
       output = [processed result]
       // call callback function and pass output result
       cb(output)
      }
     });
  }

//调用此函数写

query(type, row, column,function(output){
  console.log(output)

})