【问题标题】:How to make multiple mysql queries in Node with promises如何在 Node 中使用 Promise 进行多个 mysql 查询
【发布时间】:2015-08-30 02:05:00
【问题描述】:

万事如意,

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

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

我在这里的代码类型的示例是:(dbPool.queryOPromise 返回包装在承诺中的查询)

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});
        }                                                                                                           
    })       
})

有人对解决这种情况的最佳方法有看法吗?

谢谢!

【问题讨论】:

  • 真正的问题是什么?

标签: mysql node.js promise


【解决方案1】:

您应该返回后续的承诺,而不是在它们上调用.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. 

这是使用 Promise 的 #1 菜鸟错误。 Checkout this wonderfully written article addressing issues exactly like this

【讨论】:

  • 感谢 Lagging,这非常有帮助,可能是迄今为止我见过的关于 Promises 的最佳参考。干杯!
  • 这篇文章教会了我在生活中取得成功所需要知道的一切。比知道如何钓鱼更好。
  • 也有同样的问题,return the subsequent promise 是关键,谢谢 laggingreflex。这篇文章还教会了我如何在生活中取得成功。
  • 感谢您提供引用该主题的好文章的链接!!!您节省了我搜索有关 Promises 的其他问题的时间。
【解决方案2】:

仅适用于 node -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

你必须升级 node -v > 8.x

你必须使用 async 函数才能使用 await。

示例:

   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)
       }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-04
    • 2018-02-01
    • 1970-01-01
    • 2021-01-27
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    相关资源
    最近更新 更多