jemz jemz - 7 months ago 11
Javascript Question

Method name is not a function

I have problem in calling the method in my module.

There is an errorTypeError: usr.User.getAddress is not a function


I don't know how to fix this I think I have problem in my module code. I want to get the address or the result.

in my main.js

var mysql = require('mysql');
var usr = require('./user');

var useraddress = usr.User.getAddress (id,pool); //this is how I access the method


in my user.js

exports.User = function () {

return {
getAddress: function (userid, pool){
pool.getConnection(function (err, connection) {
var options = {
sql: " select address from user where id = ?
};

var querypos = connection.query(options, [userid], function (err, results) {
if (err) throw err;


});

});
}
};

};


Thank you in advance.

Answer

You are exporting User as a factory function which returns an object with getAddress method on it. So you need to invoke (instantiate) User first:

var useraddress = usr.User().getAddress(id, pool);

Another important problem. connection.query request is asynchronous, which means that assigning getAddress result to var useraddress doesn't make sense. Instead you need to either pass callback to getAddress or use Promise pattern (check this post for great deal of details on the topic: How do I return the response from an asynchronous call?).

In your case I think something like this would be a simplest working approach:

exports.User = function () {
    return {
        getAddress: function (userid, pool){
            pool.getConnection(function (err, connection) {
                var options = {
                    sql: "select address from user where id = ?"
                };

                var querypos = connection.query(options, [userid], function (err, results, callback, errCallback) {
                    if (err) {
                      errCallback(err);
                    }
                    callback(results);
                });
            });
        }
   };
};

and usage:

usr.User().getAddress(id, pool, function(result) {
    console.log('Loaded', result);
});
Comments