Promisifying Zookeeper 的多重回调函数

Promisifying Zookeeper's multiple callback function

Zookeeper 提供了一个 getChildren 方法,该方法在回调中接受节点的路径和 returns 该节点的子节点。它还在这个过程中设置了一个手表,并在手表被触发时调用观察者回调

getChildren(path, function(err,event){
        //this is the watcher callback
    },
    function(err,children,stats){
        //children callback
    }
)

所以如果我用bluebird的Promise.promisify来promisify这个功能。我怎么知道这个函数返回的 promise 是 watcher 还是 children ??

如果我对getChildren()接口的理解正确的话,最后一个回调被设计成用子对象列表调用一次。第一个回调是观察者回调,可以无限次调用以通知您发生的各种变化。

鉴于此,最后一个回调可能符合承诺。第一个回调不能也必须保持回调。此外,第二个回调返回多个结果(这与承诺不完全吻合)所以你也必须考虑到使用 multiArgs.spread.

所以,你可以这样做:

let getChildrenP = Promise.promisify(getChildren, {multiArgs: true});

getChildrenP(path, function(err, event) {
    // watcher event occurred here
    // this may get called multiple times
}).spread(function(children, stats) {
    // children are available now
}).catch(function(err) {
    // error here
});