Answer the question
In order to leave comments, you need to log in
Module.exports does not wait for the callback to execute. How to solve this problem?
Good afternoon! I'm new to NodeJS, there are files: main.js and db.js, I connect db.js via require, then in main I execute the function that is described in db.js, but I get undefined.
main.js:
var db = require('./db');
console.log('main.js: ' + db.test());
var mysql = require('mysql');
var db = mysql.createPool({
...
});
exports.test = function() {
db.query("SELECT COUNT(*) FROM `users`", function(error, rows){
console.log('db.js: ' + rows[0]['COUNT(*)']);
return rows[0]['COUNT(*)'];
});
}
Answer the question
In order to leave comments, you need to log in
The issue is not so much that you don't know how to prepare NodeJS, but that you don't know how to prepare asynchronous requests.
You cannot return a result from a function, as you did. db.query is an asynchronous function, the answer can come at any time, and by that time your return construct will no longer be relevant, besides, return is in a different scope (an anonymous callback in db.query). Because you don't return anything from the test function synchronously, you get undefined by default (no return is the same as return undefined).
If you do not delve into the async module, then this is how it is solved:
main.js
var db = require('./db');
db.test(function(count){
console.log('main.js: ' + count);
});
var mysql = require('mysql');
var db = mysql.createPool({
...
});
exports.test = function(callback) {
db.query("SELECT COUNT(*) FROM `users`", function(error, rows){
var count = rows[0]['COUNT(*)'];
console.log('db.js: ' + count);
(typeof callback != 'undefined') && callback(count);
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question