用于KOA和co-mysql与生成器的重构node-mysql回调

时间:2014-05-05 15:05:56

标签: mysql node.js koa

我在现有应用程序中进行如下查询,并希望有一些建议/示例,说明如何使用生成器来重构KOA + co-mysql,避免或简化sql调用的链接函数。 JS很好,当然,我使用nodejs 0.11和支持生成器的CS版本。仍在努力摆脱“新方式”。

谢谢,K

client = mysql.createPool(mysql_options)
getSql = (sql, callback) ->
  client.query sql, (err, rows, fields) ->
    if err  #mysql error handling
      if err.code isnt 'PROTOCOL_CONNECTION_LOST'
        console.log 'Mysql Error <> Conn.Lost: ',err.stack
        process.on "uncaughtException", (err) ->
          console.log "getSql Mysql Error Caught Exception: ", err.stack
          return
      else
        setTimeout ->
          console.log 'Connection Lost; Re-connecting lost client (restart delay): ',err.stack
          client = mysql.createPool(mysql_options)
          return
        , 700
    client.release
    callback rows

    q10 = ->         # and in the routes...
      sql = "select count(*) as custCount from cust01 where sessionid = '" +  prSid + "' and custNum = " + "'" + sessionLoginUser + "'"
      getSql sql, (results) ->
        q20(results[0].custCount)

    q20 = (custCount) ->
     ....etc etc

    q10()

1 个答案:

答案 0 :(得分:0)

使用co-mysql,他们的示例脚本将在CoffeeScript中(使用xixixao fork):

co = require('co')
mysql = require('co-mysql')

co( -->
  connection = mysql.createConnection options
  connection.connect()
  result = yield connection.query('SELECT 10086 + 10000 AS q')
  connection.end()
)()