-1

代码.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;

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

在 node.js 上运行

> node Test.js

我得到未触发的错误回调。

如果我能够放置这个脚本,我的理解是在我的函数返回之前: callback(computeValue);这应该可以工作恕我直言。如果我错了,请纠正我。但是,我不明白我可以在哪里插入这个。谢谢你的时间!

4

2 回答 2

1

首先,您的代码不是异步的,您需要使用 process.nextTick 或 setImmediate,并且在当前情况下,测试用例应该如下所示:

代码.js

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

exports.Util = Util;

测试.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();
于 2013-11-15T23:56:52.150 回答
0

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);
}
于 2013-11-16T23:40:42.003 回答