Promisify自定义方法

我对Node和JS世界相当陌生。 我要实现的目标是“模块化”我的查询,并在各种情况下重用它们。 这是我的dbpipe理器:

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

我如何“promisify”我的方法? 更重要的是 :这是分离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') }) } } 

你实际上离promisifying非常近:)

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

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

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

有一个很好的post,你可能想了解Promise的工作原理: https : //blog.domenic.me/youre-missing-the-point-of-promises/