Question

Code.js

var Util = function(){
    function factorial(n, callback){
        if(n == 1){
           return n;
        } else {
           return n*factorial(n-1, callback);
        }
        /*callback(returnValue); */ // Where should this line go?
    }

    return{
      factorial: factorial
    };
};

exports.Util = Util;

Test.js

var vows = require('vows'),
    assert = require('assert'),
    Util = require('./Code').Util;

var u = new Util();


vows.describe('Testing Utils').addBatch({
     'Test Factorial async':{
          topic: function(){
                u.factorial(5, this.callback);
           },
          'The output must be 120': function(result, ignore){
              assert.equal(result, 120);
           }
      }
}).run();

run on node.js

> node Test.js

I get the error callback not fired.

What I understand is just before my function returns if I am able to put this script: callback(computeValue); this should work IMHO. Please correct me If I am wrong. However, I do not understand where can I insert this. Thanks for your time!

Était-ce utile?

La solution

First of all, your code isn't asynchronous, you need to use process.nextTick or setImmediate and, in the current situation the test case should look like I wrote below:

code.js

var Util = function () {
    this.factorial = function (n) {
        if (n == 1) {
            return n;
        } else {
            return n * this.factorial(n - 1);
        }
    }
};

exports.Util = Util;

test.js

var vows = require('vows'),
    assert = require('assert'),
    Util = require('./code').Util;

vows.describe('Testing Utils').addBatch({
    'Test Factorial async': {
        topic: new Util,
        'The output must be 120': function (util) {
            assert.equal(util.factorial(5), 120);
        }
    }
}).run();

Autres conseils

After a bit of trial and error I am now able to apply recursion:

The idea is to wrap your computation inside a function so that callback(retVal) can be fired after computation is done

function factorial(n, callback){ 
    var retVal = (
           function anonymous(num) { // note it is necessary to name this anonymous function to
                              // be able to call recursively
               return (num == 1 ? num : num*anonymous(num -1));
           }
    )(n); // immediately execute with n;

// callback with retVal;
callback(retVal);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top