Node JS中没有阻塞

时间:2014-12-14 18:33:45

标签: javascript node.js asynchronous

我定义了一个从数据库中获取值的方法,我将其命名为getParam (),如下所示:

function getParam( tableName,  paramName, id){
var param=0;
var query = client.query('SELECT '+ paramName + ' AS myparam FROM  ' + tableName + ' where contest_id = ' + id);
  query.on('row', function(row) {
    param= row.myparam;
          });

return param;   

}

但我有问题;回调函数param= row.myparam;它将param作为undefined返回,然后执行回调函数function(row) { param= row.myparam;}

但是我希望首先运行回调函数然后它返回param中的值。我怎么能这样做,因为Node JS是异步的?

1 个答案:

答案 0 :(得分:2)

除非您的数据库客户端具有同步模式 - 这在节点中是一个坏主意 - 您必须使用回调或承诺进行异步操作:

function getParam( tableName,  paramName, id, callback){
  var param=0;
  var query = client.query('SELECT '+ paramName + ' AS myparam FROM  ' + tableName + ' where contest_id = ' + id);
  query.on('row', function(row) {
      param= row.myparam;
      // call the callback from here
      callback(param);
  });
  // removed your return statement, since there is nothing to return yet
  // return param;   
}

并称之为:

getParam("mytable","myparam","256", function(param) {
   // do what you want with param here
});

如果您更喜欢承诺,那么您可以做承诺风格(任何一个库都可以):

function getParam( tableName,  paramName, id){
  var param=0, defer = makeDeferSomehow();
  var query = client.query('SELECT '+ paramName + ' AS myparam FROM  ' + tableName + ' where contest_id = ' + id);
  query.on('row', function(row) {
      param= row.myparam;
      // call the callback from here
      defer.resolve(param);
  });
  // removed your return statement, since there is nothing to return yet
  // return param;   
  // instead return the promise
  return defer.promise;
}

然后你会称之为:

getParam("mytable","myparam","256").then(function(param) {
   // do what you want with param here
});