8

如何在 Bluebird 中使用 Promise 包装 Node.js 回调?这是我想出的,但想知道是否有更好的方法:

return new Promise(function(onFulfilled, onRejected) {
    nodeCall(function(err, res) {
            if (err) {
                onRejected(err);
            }
            onFulfilled(res);
        });
});

如果只需要返回一个错误,是否有更简洁的方法来执行此操作?

编辑 我尝试使用 Promise.promisifyAll(),但结果没有传播到 then 子句。我的具体例子如下所示。我正在使用两个库:a) sequelize,它返回 Promise,b) supertest(用于测试 http 请求),它使用节点样式回调。这是不使用 promisifyAll 的代码。它调用 sequelize 来初始化数据库,然后发出 HTTP 请求来创建订单。两个 console.log 语句都正确打印:

var request = require('supertest');

describe('Test', function() {
    before(function(done) {
        // Sync the database
        sequelize.sync(
        ).then(function() {
            console.log('Create an order');
            request(app)
                .post('/orders')
                .send({
                    customer: 'John Smith'
                })
                .end(function(err, res) {
                    console.log('order:', res.body);
                    done();
                });
        });
    });

    ...
});

现在我尝试使用 promisifyAll,这样我就可以将调用与 then 链接起来:

var request = require('supertest');
Promise.promisifyAll(request.prototype);

describe('Test', function() {
    before(function(done) {
        // Sync the database
        sequelize.sync(
        ).then(function() {
            console.log('Create an order');
            request(app)
                .post('/orders')
                .send({
                    customer: 'John Smith'
                })
                .end();
        }).then(function(res) {
            console.log('order:', res.body);
            done();
        });
    });

    ...
});

当我到达第二个 console.log 时, res 参数是未定义的。

Create an order
Possibly unhandled TypeError: Cannot read property 'body' of undefined

我究竟做错了什么?

4

1 回答 1

8

您没有调用承诺返回版本,也没有返回它。

试试这个:

   // Add a return statement so the promise is chained
   return request(app)
            .post('/orders')
            .send({
                customer: 'John Smith'
            })
            // Call the promise returning version of .end()
            .endAsync(); 
于 2014-03-31T12:59:56.903 回答