【问题标题】:Promisify Custom MethodPromisify 自定义方法
【发布时间】:2016-09-30 18:35:56
【问题描述】:

我对 Node 和 JS 世界还很陌生。我试图实现的是“模块化”我的查询并在各种场景中重用它们。这是我的数据库管理器:

'use strict'

const mysql = require('mysql')
var Promise = require('bluebird')
var using = Promise.using
Promise.promisifyAll(require('mysql/lib/Connection').prototype)
Promise.promisifyAll(require('mysql/lib/Pool').prototype)
const config = require('./config')

var pool = mysql.createPool({
    connectionLimit: 100,
    host: config.dbHost,
    user: config.dbUser,
    password: config.dbPassword,
    database: config.db,
    debug: config.dbDebug
})

var getConnection = function () {
    return pool.getConnectionAsync()
        .disposer(function (connection) {
            return connection.release()
        })
}

var query = function (command) {
    return using(getConnection(), function (connection) {
        return connection.queryAsync(command)
    })
}

module.exports = {
    query: query
}

在一个单独的文件中,我想调用一个查询,并根据该结果 然后 调用另一个(第二个使用第一个的结果值):

utils.method1()
    .then(function (value) {
        utils.method2(value)
    })
    .catch(function (error) {
        console.error('Error while retrieving product id: ' + error)
        res.json({ data: error })
    })

我怎样才能“承诺”我的方法? 更重要的是:这是分离 mySQL 查询的正确方法吗?您能提出一些最佳做法吗?

为了完整起见,这是我执行查询的方法1:

module.exports = {
    method1: function () {
        // ...sql
        db.query(mysql.format(sql, params))
            .then(function (results) {
                return results[0].id // clearly this is not a promise
            })
            .catch(function (error) {
                console.error('Error while retrieving...: ' + error)
                res.status(500).send('Internal server error')
            })
    }
}

【问题讨论】:

    标签: mysql node.js promise bluebird node-mysql


    【解决方案1】:

    你实际上离承诺很近了:)

    当然,results[0].id 不是一个 promise,但它是 one 的最终值。

    您应该做的是返回查询的承诺链:

    return db.query(mysql.format(sql, params))
        .then(function (results) {
            return results[0].id // clearly this is not a promise
        })
        .catch(function (error) {
            console.error('Error while retrieving...: ' + error)
            res.status(500).send('Internal server error')
        })
    

    这样做,您将返回一个承诺,该承诺将使用您的链的最后一个值解决,或者失败。您可以按照您的要求使用它:

    method1.then(function(value){
        // Here, value is results[0].id
    })
    .catch(function(err){
        // Manage a failed query
    });
    

    您可能想阅读一篇关于 Promises 工作原理的精彩帖子:https://blog.domenic.me/youre-missing-the-point-of-promises/

    【讨论】:

    • 只是一个回报。 =) 非常感谢。您如何看待这种代码骨架?
    • 我不确定如何理解您的问题。如果您在谈论代码架构,我会说保持简单。看起来你没有使用像 Sequelize 这样的 ORM(你可能想看看!)。尝试将所有 SQL 操作作为一个简单的数据访问层来管理。零业务逻辑。只需关注基本的 CRUD 操作,并将您的实体拆分为节点模块。另外,注意一致性,不断返回 Promise。如果这不是重点,那么,对不起!
    猜你喜欢
    • 2020-10-20
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多