使用蓝鸟将节点.js回调包装在承诺中

Wrapping Node.js callbacks in Promises using Bluebird

本文关键字:包装 承诺 回调 js 蓝鸟 节点      更新时间:2023-09-26

如何在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,它返回承诺,b)supertest(用于测试http请求),它使用节点样式回调。这是不使用 promisifyAll 的代码。它调用 sequelize 来初始化数据库,然后发出 HTTP 请求来创建订单。Bosth 控制台.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,以便我可以将调用与以下链接:

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

当我到达第二个控制台时.log res 参数未定义。

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

我做错了什么?

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

试试这个:

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