A
A
Alexander Solovey2016-06-02 12:30:15
Node.js
Alexander Solovey, 2016-06-02 12:30:15

How to return data from Node.js module?

A week since I started learning Node.js - I can't get data from the module. I get undefined.
If I output rows data in the module itself, it displays everything. But I need to pass data to the application where the module is connected.
There is app.js (code):

var tasks = require('./tasks');
var list = tasks.list();
console.log(list);

For it, I created the tasks.js module (code):
var mysql = require('mysql');
var pool  = mysql.createPool({
connectionLimit : 15,
host: 'localhost',
database: 'node',
user: 'node',
password: '123'
});
var Tasks = {

list: function(){
pool.getConnection(function(err, connection) {
  connection.query( 'SELECT * FROM tasks', function(err, rows) {
return rows;
connection.release();
  });

});
},

edit: function(){
},
};

module.exports = Tasks;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Damir Makhmutov, 2016-06-02
@naghtigall

The thing is that inside the tasks.list function is asynchronous code. You need something like this:

list: function(callback) {
    pool.getConnection(function(err, connection) {
        connection.query( 'SELECT * FROM tasks', function(err, rows) {
            callback(rows);
            connection.release();
        });
    });
},

And in the calling code:
var tasks = require('./tasks');
var list = tasks.list(function (rows) {
    console.log(rows);
});

And then read about Promise.

A
Alexander Solovey, 2016-06-02
@naghtigall

Thanks for the very fast response!!!! Very prompt!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question