在process.nextTick中回调未定义

时间:2014-05-26 15:10:06

标签: javascript node.js

尝试递归调用同步函数来解析数组的元素;一旦到达数组的最后一个元素,就会调用回调。但是当传递给process.nextTick时,回调被认为是未定义的,因为在回调中声明的另一个变量与回调打印正确的值。

任何人都可以解释我做错了什么;如何正确访问同一范围内的另一个变量,如何回调未定义。

someobject.prototype.launch = function (callback) {

    if (!this.config.children || this.config.children.length <= 0)
        throw new Error('No children found');
    var callCounter = 1;
    var _callback = function () {
        callback(true)
    };
    console.log(_callback); // prints [Function] as expected
    function create(i) {
        //some logic to process 
        //the 'i' element
        if (callCounter == stopAt) {
            var _callback = callback(true);
            //process.nextTick(_callback); //this too doesnt work as _callback is undefined
            process.nextTick(function () {
                console.log(callCounter + ' ' + _callback);
               // the callback is undefined where as callCounter holds the proper value. 
            });
        }else {
        //process.nextTick( (create.bind(this))(callCounter++));
        (create.bind(this))(callCounter++)
    }
     (create.bind(this))(0);
}

1 个答案:

答案 0 :(得分:2)

var _callback = callback(true); 

此字符串可以返回未定义的值。你是否回避回调(true)返回其他函数或值。删除或评论。

未定义的功能结果示例

var func_without_result = function(){};

console.log(func_without_result());

结果

> undefined