如何在Node中使用承诺进行多个MySQL查询

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (278)

所有的人,

我正在尝试将一些旧的php代码转换为Node,其中一部分工作一直试图找出对我的数据库执行SQL查询的最佳方法(我正在使用SQL,这样就可以将现有的数据库移植过来)。

我已经让它们正常工作了,但是遇到了“末日金字塔”问题,以及后续的范围问题(即返回的值不能用于后续的“s”)。

这里的代码类型的一个例子是:(dbPool.queryOPromises返回一个以承诺包装的查询)

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});
        }                                                                                                           
    })       
})
提问于
用户回答回答于

你应该回归后来的承诺而不是.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. 
用户回答回答于
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>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)
       }

扫码关注云+社区

领取腾讯云代金券