CocoHot
CocoHot

Reputation: 1226

NodeJS function execute order

Just start learn Node and trying to build an app.

Right now in my route file I'm trying to connect to mysql and get the major of the user and then used it to do other stuff. However when I execute the webpage the console shows that the second log execute earlier than the first one. I guess this might because Node is Async?

exports.list = function(req, res){
req.getConnection(function(err,connection){
   /* find user's major */
    var user_major = (function() {
        connection.query('SELECT major FROM user WHERE user_id=' + req.params.id, function (err, row) {
            if (err) {
                console.log("Error Selecting : %s ", err);
            }
            console.log('Test inside function: '+ row[0].major);
            return row[0].major;
        });
    })();
    console.log("Test outside: " + user_major);

    res.render('main/main',{page_title:'USER MAJOR', data: user_major});
    });
};

Terminal log:

Test outside: undefined
GET /main/1 304 353.737 ms - -
Test inside function: COEN

Upvotes: 0

Views: 1398

Answers (2)

Ben Fortune
Ben Fortune

Reputation: 32127

As the others have pointed out in the comments, Node.js is asynchronous. You can't just return data from a function, it has to be returned in a callback.

I'd rewrite it as follows:

exports.list = function(req, res, next) {
    req.getConnection(function(err, connection) {
        if (err) return next(err);
            /* find user's major */
        var user_major = function(id, callback) {
            connection.query('SELECT major FROM user WHERE user_id=' + id, function(err, row) {
                if (err) {
                    return callback("Error Selecting : %s ", err);
                }
                callback(null, row[0].major);
            });
        };

        user_major(req.params.id, function(error, major) {
            if (error) return next(error);
            res.render('main/main', {
                page_title: 'USER MAJOR',
                data: major
            });
        });

    });
};

Upvotes: 3

Ashok Kumar Sahoo
Ashok Kumar Sahoo

Reputation: 580

You are facing the problem because when the call stack reaches console.log, the value is yet to be returned, since node js is async. Callbacks are used to call back a callback function with a result of the async function.

    exports.list = function(req, res){
    req.getConnection(function(err,connection){
       /* find user's major */

      var callback = function(user_major){
     console.log("1 Test outside: " + user_major);
     res.render('main/main',{page_title:'USER MAJOR', data: user_major});
     }

        var db_call_for_user_major = (function(callback) { 
            connection.query('SELECT major FROM user WHERE user_id=' + req.params.id, function (err, row) {
                if (err) {
                    console.log("Error Selecting : %s ", err);
                }
                console.log('test inside function: '+ row[0].major);
                return callback(row[0].major);
            });
        })();

        });
    };

Upvotes: -1

Related Questions