Sritharan M
Sritharan M

Reputation: 43

pass outer scope logic to a callback function javascript nodejs

/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);
        }
    });
}

When I try to pass the sampleFunction as a callback function to the forEachFunction, but still maintaining the state of the outer function, I am getting an error as "undefined as not a function" Pls help ??

Upvotes: 0

Views: 74

Answers (1)

Bergi
Bergi

Reputation: 664548

You are using the function before you define it! Swap those two statements:

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

asyncFileObjectReader.forEachFunction(filesObject, sampleFunction);

Oh, and there's really no reason to make sampleFunction global to your module. Especially as you use mapContainer and root_directory as closure variables, in an async function. This would lead to horrible race conditions if allAcitemFileIterator is called too fast. So please use var sampleFunction = …, or just a function declaration.

Upvotes: 2

Related Questions