将外部范围逻辑传递给回调函数javascript nodejs

时间:2015-06-27 20:53:19

标签: javascript node.js

/file_iterator.js

var asyncFileObjectReader = require('../core/async_forEach_Array.js')
var sampleFunction;

function allAcitemFileIterator(filesObject, mapContainer, root_directory) {     

    asyncFileObjectReader.forEachFunction(filesObject, sampleFunction);

    sampleFunction = function (fileName) {
        mapContainer.set(basePathAlterColons.removeBasePathAlterColons(fileName, root_directory), 
            extractUriFromList.extractUriFromList(getReferences.getReferences(fileName)));
    }
}

/async_foreach_Array.js

function forEachFunction(filesObject, filesObjectFunction) {
    filesObject.forEach(function (fileName) {
        if (path.extname(fileName) === acitem_file_extension) {
            filesObjectFunction(fileName);
        }
    });
}

当我尝试将sampleFunction作为回调函数传递给forEachFunction,但仍保持外部函数的状态时,我收到一个错误,因为"未定义为不是函数"请帮忙??

1 个答案:

答案 0 :(得分:2)

您在定义之前使用该功能!交换这两个陈述:

sampleFunction = function (fileName) {
    mapContainer.set(basePathAlterColons.removeBasePathAlterColons(fileName, root_directory), 
        extractUriFromList.extractUriFromList(getReferences.getReferences(fileName)));
};

asyncFileObjectReader.forEachFunction(filesObject, sampleFunction);

哦,并且没有理由让sampleFunction全局到您的模块。特别是在异步函数中使用mapContainerroot_directory作为闭包变量时。如果调用allAcitemFileIterator太快,这将导致可怕的竞争条件。所以请使用var sampleFunction = …,或仅使用函数声明。