手动宣传与Bluebird的pg.connect

时间:2014-05-27 04:25:31

标签: node.js promise bluebird node-postgres

我想宣传node-postgres'pg.connect方法以及回调中提供的内部connection.query方法。

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

问题是,我不确定这段代码是否正确或是否应该改进?代码正在运行,我只是想知道我是否正在使用Bluebird。

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

4 个答案:

答案 0 :(得分:4)

抛弃所有可怕的回调代码,然后在应用程序初始化中的某处执行此操作:

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

答案 1 :(得分:4)

到目前为止,有许多图书馆会为您执行此操作:

答案 2 :(得分:3)

bluebird 3的更新

pg.connectAsync(...).spread(function(connection, release) { ... })调用将不再有效,因为bluebird的API已更改:http://bluebirdjs.com/docs/new-in-bluebird-3.html#promisification-api-changes

问题是bluebird 3中的promisifyAll默认情况下不处理多个参数。这导致.spread()调用报告类似于以下的TypeError:

TypeError: expecting an array or an iterable object but got [object Null]

要解决此问题,您可以为connect / connectAsync明确启用多个参数。在上述所有宣传内容之后执行以下操作:

...
pg.connectAsync = Promise.promisify(pg.connect, { multiArgs: true });

答案 3 :(得分:0)

我建议稍微修改Petka Antonov解决方案

#include <stdio.h>
#include <time.h>

int main(int argc, char *argv[])
{
    int h=0;
    int m=0;
    int d=0;
    int ht=0;
    int t=0;

    printf("Starting Hour: ");

    do
    {
        scanf("%d", &h);
    }
    while (h > 0 && h < 24);

    printf ("Invalid input. Please use 24hr format\n");
    printf ("Starting Hour: ");
    scanf("%d",&h);

    printf("Starting Minute: ");
    scanf("%d",&m);
    printf("Starting Time is %d:%d, what is the duration? ", h, m);
    scanf("%d",&d);
    t=(m+d);
    ht=t/60;
    h=(h+ht)%24;
    m=t%60;

    printf("Ending Time: %d:%d",h,m);
    printf("\n");

    getchar();
    return 0;
}

此处var Promise = require('bluebird'); var pg = require('pg'); Object.keys(pg).forEach(function (key) { var Cls = null; try { Cls = pg[key]; if (typeof Cls === 'function') { Promise.promisifyAll(Cls.prototype); Promise.promisifyAll(Cls); } } catch (e) { console.log(e); } }); Promise.promisifyAll(pg); 已被'pg[key]阻止,因为try-catch在尝试访问pg[key]时可以重新error