I would like to use the fantastic async module to write some nice Javascript code for NodeJS. I've got an array of values and I want to call a particular function on each value and to accumulate the results in an array: I use async.map for this. Unfortunately, if the function I try to call is a prototype function of my class, it fails to read variable values.
Example This is a test "class" I've defined.
var async = require('async');
function ClassA() {
this.someVar = 367;
};
ClassA.prototype.test1 = function(param, callback) {
console.log('[' + param + ']The value in test is: ' + this.someVar);
callback(null, param + this.someVar);
};
ClassA.prototype.test2 = function() {
var self = this;
async.map([1,3,4,5], (self.test1), function(err, result){
if (err) {
console.log('there was an error')
} else {
console.log('Result is: ' + result)
}
})
};
module.exports = new ClassA();
And this is how I use it
testclass.test1(1, function(err, data){});
testclass.test2();
That's the output:
[1]The value in test is: 367
[1]The value in test is: undefined
[3]The value in test is: undefined
[4]The value in test is: undefined
[5]The value in test is: undefined
Result is: NaN,NaN,NaN,NaN
As you can see the output obtained through test2
which makes use of async.map
cannot access the this.someVar
variable.
Questions I am definitely missing something here. Can somebody point me to the error and explain why it is not working? I would expect 367 to appear in place of those undefined. I think the problem is related to this SO question, but I can't seem to find a solution for my use case.
Thanks for reading and sorry for the length of the question!