如何使用promises在Node中进行多个mysql查询

时间:2015-06-14 14:31:19

标签: mysql node.js promise

G'day all,

我正在尝试将一些旧的PHP代码转换为Node,并且部分旅程一直试图找出对我的数据库执行sql查询的最佳方法(我正在使用SQL以便我可以移植现有的数据库结束。)

我已经让他们工作了,但遇到了“末日金字塔”问题,并且随后的范围问题(即返回的值不能随后用于“当时”)。

我在这里的代码类型的一个示例是:(dbPool.queryOPromise返回包含在promise中的查询)

dbPool.queryOPromise(query)                                                                                     
.then(function(result){                                                                                         
    console.log(result);                                                                                          
    var query = {                                                                                                 
        sql:"INSERT INTO newusers (newuserid, ipaddress, email) VALUES (?,?,?)",                                    
        values: [newuserid, ipAddress, email]                                                                       
    };                                                                                                            
    dbPool.queryOPromise(query)                                                                                   
    .then(function(value){                                                                                        
        console.log(value);                                                                                         
        if(value.code==200) {                                                                                       
            res.status(200).json({code:200, status:"New User Created"});                                              
        } else {                                                                                                    
            res.status(400).json({code:value.code, status:"Error creating new user: ".value.status});
        }                                                                                                           
    })       
})

有没有人对攻击这种情况的最佳方法有看法?

谢谢!

2 个答案:

答案 0 :(得分:5)

你应该 返回 后续的承诺,而不是在他们身上调用.then

dbPool.queryOPromise(query)
.then(function(result) {
    console.log(result);
    var query = {
        sql: "INSERT INTO newusers (newuserid, ipaddress, email) VALUES (?,?,?)",
        values: [newuserid, ipAddress, email]
    };
    // RETURN the second promise, 
    return dbPool.queryOPromise(query);
})
.then(function(value) {
    console.log(value);
    if (value.code == 200) {
        res.status(200).json({code: 200, status: "New User Created"});
    } else {
        res.status(400).json({code: value.code, status: "Error creating new user: ".value.status });
    }
})
.catch(console.error); // and always catch the errors at the end. 

这是使用承诺的第一个新手错误。 Checkout this wonderfully written article addressing issues exactly like this

答案 1 :(得分:0)

对于节点-v>仅限8.x, 分享我的工作实例:

我使用此Promisified MySQL middleware for Node.js

阅读这篇文章Create a MySQL Database Middleware with Node.js 8 and Async/Await

这是我的database.js

var mysql = require('mysql'); 

// node -v must > 8.x 
var util = require('util');


//  !!!!! for node version < 8.x only  !!!!!
// npm install util.promisify
//require('util.promisify').shim();
// -v < 8.x  has problem with async await so upgrade -v to v9.6.1 for this to work. 



// connection pool https://github.com/mysqljs/mysql   [1]
var pool = mysql.createPool({
  connectionLimit : process.env.mysql_connection_pool_Limit, // default:10
  host     : process.env.mysql_host,
  user     : process.env.mysql_user,
  password : process.env.mysql_password,
  database : process.env.mysql_database
})


// Ping database to check for common exception errors.
pool.getConnection((err, connection) => {
if (err) {
    if (err.code === 'PROTOCOL_CONNECTION_LOST') {
        console.error('Database connection was closed.')
    }
    if (err.code === 'ER_CON_COUNT_ERROR') {
        console.error('Database has too many connections.')
    }
    if (err.code === 'ECONNREFUSED') {
        console.error('Database connection was refused.')
    }
}

if (connection) connection.release()

 return
 })

// Promisify for Node.js async/await.
 pool.query = util.promisify(pool.query)



 module.exports = pool

您必须升级节点-v&gt; 8.x

您必须使用异步功能才能使用等待。

示例:

   var pool = require('./database')

  // node -v must > 8.x, --> async / await  
  router.get('/:template', async function(req, res, next) 
  {
      ...
    try {
         var _sql_rest_url = 'SELECT * FROM arcgis_viewer.rest_url WHERE id='+ _url_id;
         var rows = await pool.query(_sql_rest_url)

         _url  = rows[0].rest_url // first record, property name is 'rest_url'
         if (_center_lat   == null) {_center_lat = rows[0].center_lat  }
         if (_center_long  == null) {_center_long= rows[0].center_long }
         if (_center_zoom  == null) {_center_zoom= rows[0].center_zoom }          
         _place = rows[0].place


       } catch(err) {
                        throw new Error(err)
       }