如何使用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,它返回promises,b)supertest(用于测试http请求),它使用节点样式的回调。这是不使用promisifyAll的代码。它调用sequelize初始化数据库,然后发出HTTP请求来创建订单。正确打印Bosth 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
我做错了什么?
答案 0 :(得分:8)
您没有调用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();