丢掉所有可怕的回调代码,然后在应用程序初始化的某个位置执行此操作:
var pg = require("pg");var Promise = require("bluebird");Object.keys(pg).forEach(function(key) { var Class = pg[key]; if (typeof Class === "function") { Promise.promisifyAll(Class.prototype); Promise.promisifyAll(Class); }})Promise.promisifyAll(pg);以后在任何地方都可以使用pg模块,就好像它被设计为使用promises开头:
// Later// Don't even need to require bluebird herevar pg = require("pg");// Note how it's the pg API but with *Async suffixpg.connectAsync(...).spread(function(connection, release) { return connection.queryAsync("...") .then(function(result) { console.log("rows", result.rows); }) .finally(function() { // Creating a superfluous anonymous function cos I am // unsure of your JS skill level release(); });});


