使用Bluebird在承诺中包装Node.jscallback
如何在Bluebird中使用Promise包装Node.jscallback? 这是我想出的,但想知道是否有更好的方法:
return new Promise(function(onFulfilled, onRejected) { nodeCall(function(err, res) { if (err) { onRejected(err); } onFulfilled(res); }); });
如果只有一个错误需要返回,是否有更干净的方法来做到这一点?
编辑我试图使用Promise.promisifyAll(),但结果不被传播到then子句。 我的具体例子如下所示。 我正在使用两个库:a)sequelize,它返回承诺,b)supertest(用于testinghttp请求),它使用节点样式callback。 这里是没有使用promisifyAll的代码。 它调用sequelize初始化数据库,然后发出HTTP请求来创build订单。 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,这样我就可以将这些调用链接起来:
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
我究竟做错了什么?
你没有调用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();