Async, promises, exports a query to the database. How?

Good time of day. There is a model to retrieve data, type:
var data = {};
data.one = function(){};
data.two = ...
module.exports = data;

In data.one I want to query the DB and get the response:
connection.query('SELECT balance FROM Users WHERE id = ?', id, function(error, result, fields){
if(error)
throw(error);
 return result;
 });

Now, due to async I got this thing no time to run and the module is not getting required data.
How do I deal with this? Promises looking, but have little idea how to apply them in this case.
August 19th 19 at 23:03
3 answers
August 19th 19 at 23:05
Now, due to async I got this thing no time to run and the module is not getting required data.

Not async, and because of misunderstanding async.
Your return is useless here. If I understand correctly, you something need:
//model.js
var data = {};
data.one = function(){};
data.two = ...
module.exports = data;

//connect.js
var model = require('./model');

connection.query('SELECT balance FROM Users WHERE id = ?', id, function(error, result, fields){
 if(error) {
throw(error);
}
 model.one(result, fields);
 //model.two(result, fields);
});

And promises naguglit themselves. Better to know what it is, and not copy-paste ready ))
No, I need something like this:
data.one = function(){
connection.query('SELECT balance FROM Users WHERE id = ?', id, function(error, result, fields){
if(error) {
throw(error);
}
return result;
})
}; - christian.Schimmel45 commented on August 19th 19 at 23:08
August 19th 19 at 23:07
Learn async/await - should help.
August 19th 19 at 23:09
data.one = function() {
 return new Promise(function(resolve, reject){
 connection.query('SELECT balance FROM Users WHERE id = ?', id, function(error, result, fields) {
 if(error) reject(error);
resolve(result);
});
});
};

// import is a miracle in another file and use:
var model = require('./model');
model.one().then(function(result) {
console.log(result);
}).catch(function(err) {
 throw err;
});

Find more questions by tags Asynchronous programmingJavaScriptNode.js