使用Promise api与Node Mysql无法正常工作

时间:2016-08-09 14:15:30

标签: javascript node.js promise node-mysql

我可以使用以下代码运行sql查询并从MySql数据库中获取记录

var mySql = require("mysql");

var connection = mySql.createConnection({
  host : "localhost",
  user : "root",
  password : "rahul",
  database : "testDb" //schema
});

connection.connect();

connection.query("select * from departmentTbl",function(err,rows,fields){

  if(err){
    console.log(err.stack);
  }

  for(var i = 0; i < rows.length; i++){     
    console.log("DepartmentId : \'"+rows[i]["deptId"]+"\', DepartmentName \'"+rows[i]["deptName"]+"\'");
  }
});

connection.end();

但是如果我使用A + Promise api A+ Promise API

我就无法运行代码

如下图所示,

var Promise = require("promise");

var mySql = require("mysql");

var connection = mySql.createConnection({
  host : "localhost",
  user : "root",
  password : "rahul",
  database : "testDb" //schema
});

var p  = Promise.resolve(connection.connect());


var sqlQuery = p.then(function(con){
  return Promise.resolve(con.query);
});

sqlQuery.then(function(q){

 q("select * from departmentTbl").then(function(err,row,fields){
   if(err){
    console.log(err.stack);
   }

   for(var i = 0; i < rows.length; i++){        
    console.log("DepartmentId : \'"+rows[i]["deptId"]+"\', DepartmentName \'"+rows[i]["deptName"]+"\'");
   };

  }).done(function(){
    connection.end();   
 });
});

请告诉我哪里出错了,为什么我无法解决承诺。

我的代码甚至不会抛出错误

1 个答案:

答案 0 :(得分:0)

我能够使用以下实现解决mysql Node和PromiseJS,如下所示,

 var Promise = require("promise");

 var mySql = require("mysql");

    var connection = mySql.createConnection({
    host : "localhost",
    user : "root",
    password : "rahul",
    database : "testDb" //schema
});

connection.connect();

var getDepartments = function(){
  return new Promise(function(resolve,reject){
    connection.query("select * from departmentTbl",function(err,rows,fields){

        if(err){                
            return reject(err);
        }else{              
            return resolve(rows);
        }

    }); // query
  }); // Promise
} // getDepartments

getDepartments().then(function(rows){   
  for(var i = 0; i < rows.length; i++){     
    console.log("DepartmentId : \'"+rows[i]["deptId"]+"\', DepartmentName \'"+rows[i]["deptName"]+"\'");
  } 
}).catch(function(e){
  console.log(e.stack);
});

connection.end();