Node.js - Function returning the value of the query?

2

This is the following I tried to search but I did not find any solution, so I tried to create a function in the model of my application that will return the data of the query in the database. This function would be called in my controller which would later be sent to the page file.

Query function

exports.show = function(){
    var result;
    connection.getConnection(function(err, connection){
        connection.query('select 1 + 1 as teste', function(err, rows){
            this.result = rows[0].teste;
            connection.release();
            console.log('---->', this.result);
            return this.result;
        });
    });
};

Controller

var Model = require('../models/Models');

exports.Index = function(request, response){
    response.pageInfo = {};

    response.pageInfo.title = 'Users';
    response.pageInfo.users = Model.show(); 
    response.render('user/index', response.pageInfo);
};

And the .jade page

extends ../layout
block content
    h1 #{users}

And by running that way it just does not print the value on the page, but it works on the console.

    
asked by anonymous 09.08.2015 / 22:50

1 answer

2

I'm going to reply without being sure, because I do not know for example what BD you are using.

The first problem I see is when you call:

response.pageInfo.users = Model.show(); 

This will get code that is asynchronous. That is, this code will make a call to the database but the rest of the code will not wait! That is: response.render('user/index', response.pageInfo); will be run before BD's response back.

Then there's another problem there: when you do return this.result; this will not return anything to response.pageInfo.users = . First because it is within 2 functions and the return does not both give return , only the one where return is; and secondly because this is asynchronous and response.pageInfo.users = already has value and the code has already run.

What to do?

Use a callback that allows you to use the information / data when it is ready.

I think in Jade you have to use the data in the second parameter of response.render and not as property of response .

Code hint:

exports.show = function(callback){
    var result;
    connection.getConnection(function(err, connection){
        connection.query('select 1 + 1 as teste', function(err, rows){
            this.result = rows[0].teste;
            connection.release();
            console.log('---->', this.result);
            return callback(this.result);
        });
    });
};

Controller

var Model = require('../models/Models');

exports.Index = function(request, response){
    Model.show(function(users){
        response.render('user/index', {
            users: users,
            title: 'Users'
        });
    }); 
};
    
10.08.2015 / 11:00