Again this Promis?

I have this model here:
connection = require('../lib/mysql');
var info = {};
var getBalance = function(id) {
 return new Promise(function(resolve, reject){
 connection.query('SELECT balance FROM Users WHERE id = ?', id, function(error, result, fields) {
if(error)
reject(error);
if(result[0]['balance'])
resolve(result[0]['balance']);
reject();
});
});
};
info.getBalance = function(id) {
getBalance(id).then(function(data){
console.log(data);
 return data;
});
}
module.exports = info;


In another file I do:
var model = require('./model');
console.log(model.getBalance(123123));


And he gives me underfind, although console.log(data) prints the desired result in that file. How to avoid this?
August 19th 19 at 23:04
1 answer
August 19th 19 at 23:06
Solution
You forgot to return promis
info.getBalance = function(id) {
 return getBalance(id).then(function(data){
console.log(data);
 return data;
});
}
Thank you! However I have now it returns the actual function of a promis, not a response from him:
Promise { } - christian.Schimmel45 commented on August 19th 19 at 23:09
Right, next you need model.getBalance(123123).then(data => console.log(data)) - Bobby_Rodriguez45 commented on August 19th 19 at 23:12
: Yes, it works. But if I want to assign this value to a variable, how would I do it? Tried let a = model.getBalance(123123).then(data => return data);
But goes bad - christian.Schimmel45 commented on August 19th 19 at 23:15
: You are attempting an asynchronous action to make synchronous. But I understand what You want to do. There are two ways:
  1. Write your logic in the colback of the promis model.getBalance(123123).then(data => {let a = data; /* your logic */})
  2. To use async await
- Bobby_Rodriguez45 commented on August 19th 19 at 23:18
About the first thing I realized about the second - it is only in es6 there? In es5 you need some library to connect? - christian.Schimmel45 commented on August 19th 19 at 23:21
: async/await is es2017 (es8), on node7, you can include the flags, so you can compile Babel in es2015 generators - kara commented on August 19th 19 at 23:24

Find more questions by tags JavaScriptNode.js