简体   繁体   中英

Javascript 'undefined' variable when using async.map on prototype functions

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!

I'm not an expert in that library (in fact, I have never used it).

But looking at this section in its docs, I think that the problem lies in the fact that what you are passing to the iterator is the function itself, but async calls that function in it's own context, meaning that the this parameter inside your function isn't the one you are expecting.

Try following the docs advice (using bind) to avoid this pitfall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM