简单的功能包装链?

时间:2014-09-23 18:49:42

标签: promise bluebird

例如,A是具有遵循node.js约定的API的现有对象:

function A() {
}

A.prototype.op = function (cb) {
    cb(undefined, 'success');
};

A.prototype.op2 = function (cb) {
    cb(undefined, 'success 2');
};

A.prototype.log = function(r) {
    console.log(r);
};

当我执行Promise.promisifyAll(A.prototype)时,我会生成*Async()个生成函数 我希望有一个像这样的可读链:

Promise.bind(a)
.then(a.opAsync)
.then(a.op2Async)
.then(a.log);

我知道这不起作用,因为我们需要额外的函数包装器返回promise:

Promise.bind(a).then(function() {
    return this.opAsync();
}).then(function(){
    return this.op2Async();
}).then(function(r) {
    this.log(r);
});

我是否必须为每个宣传的功能编写包装器?或者有更好的方法来设计这个API?

1 个答案:

答案 0 :(得分:0)

向原始函数添加虚拟参数解决了问题。

A.prototype.op2 = function (x, cb) {
    cb(undefined, 'success 2');
};

Working example

Issue with details