Wrapping Node.js Callbacks in Promises Using Bluebird

How do I call a Node.js callback using a promise in Bluebird? This is what I came up with but wanted to know if there is a better way:

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

Is there a cleaner way to do this if I need to return only an error?

Edit I tried using Promise.promisifyAll (), but the result does not apply to the then clause. My specific example is shown below. I use two libraries: a) sequelize, which returns promises, b) supertest (used to test HTTP requests), which uses node callbacks. Here's the code without using promisifyAll. It calls sequelize to initialize the database, and then makes an HTTP request to create the order. Bosth console.log instructions printed correctly:

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

Now I am trying to use promisifyAll so that I can bind the calls with:

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

When I go to the second console.log, the argument is res undefined.

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

What am I doing wrong?

+8
javascript promise bluebird
source share
1 answer

You do not invoke a promise that returns a version, or return it.

Try the following:

  // 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(); 
+8
source share

All Articles