Aroll605
Aroll605

Reputation: 386

Returned object undefined from module function

This has to be a scope issue that I'm not familiar with. I have a small module I've written as so:

(function () {

    var getPlanInfo = function (id, conn) {
        conn.query('SELECT * FROM `items` WHERE `id` = ?', [id], function (error, result) {
            if (error) console.error('Query error: ' + error.stack);

            console.log(result[0]); // Everything is great

            return result[0];
        });
    };

    modules.exports.getPlanInfo = function (id, conn) { return getPlanInfo(id, conn); // Typo }

})();

Here comes the problem. When I call it from anywhere (inside the module itself or another file), the return value is always undefined. I checked from within the function, the query returns the result as expected.

var backend = require('./module.js');
var t = backend.getPlanInfo();

t is undefined. This is the same if I call that method from inside the module itself (another function within that module).

I'm familiar with the callback principle in javascript and how objects and functions have to be passed around as an argument to remain in scope. Is this the issue here or is this a node.js particularity?

I tried in in the Developer Console (Chrome), works as expected.

Upvotes: 0

Views: 777

Answers (2)

jfriend00
jfriend00

Reputation: 707706

conn.query() looks like it is async. Thus, you can't return its result from getPlanInfo() because getPlanInfo() returns long before the result is available. Returning result[0] from the conn.query() callback just returns a piece of data back into the conn.query() infrastructure. getPlanInfo() has long before already returned.

If you want an async result, then you will have to change getPlanInfo() to use a mechanism that supports getting async results such as a direct callback or a promise or something like that.

Here's a plain callback way:

var getPlanInfo = function (id, conn, callback) {
    conn.query('SELECT * FROM `items` WHERE `id` = ?', [id], function (error, result) {
        if (error) {
            console.error('Query error: ' + error.stack);
            callback(error);
            return;
        }

        console.log(result[0]); // Everything is great

        callback(0, result[0]);
    });
};

modules.exports.getPlanInfo = getPlanInfo;

Then, the caller of that module would look like this:

var m = require('whatever');
m.getPlanInfo(id, conn, function(err, result) {
    if (err) {
        // error here
    } else {
        // process result here
    }
});

Upvotes: 2

Frax
Frax

Reputation: 5880

You don't return anything from getPlanInfo. Probably you wanted to write modules.exports.getPlanInfo = function (id, conn) { return getPlanInfo; }

(with return getPlanInfo; instead of return getPlanInfo();)

Upvotes: 1

Related Questions