使用 Bluebird 手动承诺 pg.connect [英] Manually promisifying pg.connect with Bluebird

查看:24
本文介绍了使用 Bluebird 手动承诺 pg.connect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想承诺 node-postgres 的 pg.connect 方法以及回调中提供的内部 connection.query 方法.

I want to promisify node-postgres' pg.connect method along with the inner connection.query method provided in the callback.

我可以.promisify后者,但我需要手动实现第一个(如果我在这里遗漏了什么,请解释).

I can .promisify the latter, but I need to implement the first one manually (if I'm missing something here, please explain).

问题是,我不确定这段代码是正确的还是应该改进?代码正在运行,我只是想知道我是否按预期使用 Bluebird.

The thing is, I'm not sure if this code is correct or should be improved? The code is working, I just want to know if I'm using Bluebird as meant.

// aliases
var asPromise = Promise.promisify;

// save reference to original method
var connect = pg.connect.bind(pg);

// promisify method
pg.connect = function (data) {
  var deferred = Promise.defer();

  connect(data, function promisify(err, connection, release) {
    if (err) return deferred.reject(err);

    // promisify query factory
    connection.query = asPromise(connection.query, connection);

    // resolve promised connection
    deferred.resolve([connection,release]);
  });

  return deferred.promise;
};

推荐答案

扔掉所有那些可怕的回调代码,然后在应用程序初始化的某个地方执行此操作:

Throw all that horrible callback code away, then do this somewhere in your application initialization:

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 模块,就好像它被设计为使用 Promise 一样:

Later in anywhere you can use the pg module as if it was designed to use promises to begin with:

// Later
// Don't even need to require bluebird here
var pg = require("pg");
// Note how it's the pg API but with *Async suffix
pg.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();
         });
});

这篇关于使用 Bluebird 手动承诺 pg.connect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆