将Q迁移到BlueBird(或誓言)

Mic*_*ael 6 node.js promise q bluebird

我目前在Node/amqp应用程序中使用Q promise库.我已经读过Q对像BlueBird或Vow这样的库的表现......不太好.

不幸的是,我无法弄清楚如何使用BlueBird(或Vow)来替换我目前的Q使用模式.

这是一个例子:

this.Start = Q(ampq.connect(url, { heartbeat: heartbeat }))
    .then((connection) => {
        this.Connection = connection;
        return Q(connection.createConfirmChannel());
    })
    .then((channel) => {
        this.ConfirmChannel = channel;
        channel.on('error', this.handleChannelError);
        return true;
    });
Run Code Online (Sandbox Code Playgroud)

我应该提到 - 我正在使用TypeScript ...在这个例子中,我正在接受amqplib的承诺,并从中创建一个Q承诺(因为我不喜欢amqplib的承诺).我如何使用BlueBird或Vow做到这一点?

另一个例子是:

public myMethod(): Q.Promise<boolean> {
    var ackDeferred = Q.defer<boolean>();

    var handleChannelConfirm = (err, ok): void => {
        if (err !== null) {
            //message nacked!
            ackDeferred.resolve(false);
        }
        else {
            //message acked
            ackDeferred.resolve(true);
        }
    }

     ...some other code here which invokes callback above...

    return ackDeferred.promise;
}
Run Code Online (Sandbox Code Playgroud)

这种模式是如何实施的?

所以我的一般问题是:

  1. 我读过的性能差异是真的吗?
  2. 我如何从Q迁移到BlueBird或Vow,重点关注这两种模式(但是使用'then'的解释也会很棒)?

Ben*_*aum 12

是的,Bluebird比Q快两个数量级,并且可调试性更强.您可以自己查看基准测试.

至于代码:

  • Q()Promise.resolve在Bluebird中映射(就像在ES6本机承诺中一样).*
  • Q.defer映射到Promise.defer()尽管使用promise构造函数或自动promisification是一个更好的选择,如本答案中所述.简而言之,promise构造函数是安全的.

注意* - 一旦你投下了承诺,它会自动吸收来自其他图书馆的版本 - 所以这很好:

this.Start = Promise.resolve(ampq.connect(url, { heartbeat: heartbeat }))
.then((connection) => {
    this.Connection = connection;
    return connection.createConfirmChannel());
})
.then((channel) => {
    this.ConfirmChannel = channel;
    channel.on('error', this.handleChannelError);
    return true;
});
Run Code Online (Sandbox Code Playgroud)