Answer the question
In order to leave comments, you need to log in
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);
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
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();
});
});
},
var tasks = require('./tasks');
var list = tasks.list(function (rows) {
console.log(rows);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question