Search code examples
node.jsbluebird

bluebird promisifyAll() and then() not working together with node require


I'm using Promises for the first time, so please bear with me.

Basically, I'm not seeing the function in my .then() statement being called.

When I call t.t(), is it working correctly.

When I call t.tAsync(), t() is again called.

However the result isn't being passed into the then when I call t.tAync().then(console.log);

Here is my node module:

'use strict';
var t = function(){
    console.log('inside t()');
    return 'j';
};

module.exports = {
    t: t
};

And here is my demo script:

'use strict';

require('should');
var Promise = require('bluebird');
var t = require('../src/t');

Promise.promisifyAll(t);

/*
    Call t() once to demonstrate.
    Call tAsync() and see t() is called
    Call tAsync.then(fn), and then isn't called


 */


// this works as expected, calling t()
console.log('calling t()...' + t.t());

// this also works, calling t()
t.tAsync();

// the then() statement isn't called
t.tAsync().then(function(res){
    // I expect this to be called
    console.log('HHHUUUZZZAAAHHH' + res);
});


/*
    Keep the script running 5 seconds
 */

(function (i) {
    setTimeout(function () {
        console.log('finished program');
    }, i * 1000)
})(5);

And here is the output from the test:

inside t()
calling t()...j
inside t()
inside t()
finished program

Solution

  • Your then clause will never be called because the tAsync is expecting t to call the callback not return a value.

    promisifyAll wraps Node.JS aysynchronous API's so the function it is wrapping needs to conform to the Node.JS callback signature:

    function t(callback) {
      callback(null, 'j');
    }
    

    However, I suspect based on your code that you do not want promiseifyAll but instead try() or method():

    function t() {
      return 'j';
    }
    
    Promise.try(t).then(function(result) {
      console.log(result);
    });
    

    OR

    var t = Promise.method(function() {
      return 'j';
    });
    
    t().then(function(result) {
      console.log(result);
    });
    

    For contrast the above is Bluebird.js specific. To perform this with generic Promises you would approach it one of two ways:

    Using the Promise constructor:

    function t() {
      return new Promise(function(resolve, reject) {
        resolve('j');
      });
    }
    
    t().then(function(result) {
      console.log(result);
    });
    

    Or, use the then chaining feature:

    function t() {
      return 'j';
    }
    
    Promise.resolve()
      .then(t)
      .then(function(result) {
        console.log(result);
      });