I
I
inspiredman2015-08-14 17:04:07
MySQL
inspiredman, 2015-08-14 17:04:07

[Node.JS] [node-mysql] How to return a function value?

There is a function:

function check_session(id, sess, callback) {
   pool.getConnection(function(err, connection) {
       mysqlUtilities.upgrade(connection);
       mysqlUtilities.introspection(connection);
       connection.queryRow("select * from `users` where `id`="+id+" AND `session`='"+sess+"'", [], function(err, row) {
         if(row==false) callback(0);
           else callback(1);
       });
    });
}

As well as its use:
io.on('connection', function(socket){
    console.log('connected');
    check_session(19,'1e7d10bb50278502f530d8ca3cc47071', function(result){
       console.log(result); // я могу только так принимать и обрабатывать, а return result показывает undefined
    });
});

How to make it so that you can use this function in the form:
if(check_session(19,'1e7d10bb50278502f530d8ca3cc47071')) {
...
} else {
....
}

I understand that the question is stupid, I met NodeJS yesterday, but still, I ask you to answer specifically, without references to literature. Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Shemsedinov, 2015-08-14
@MarcusAurelius

Don't worry, just accept the fact that in node.js it is customary to do all the functions that work with the network, files and databases in an asynchronous style, i.e. they return values ​​not through return, but through callback. Move your if to a callback, or rather, declare a function and pass it as a callback parameter so that the nesting does not grow. Get used to...

S
Sergey, 2015-08-14
Protko @Fesor

no references to literature

I give a link to the article, because the only sane way to do what you want is coroutines and I think it's too early for you. And awaitable in JS still xs when they appear.
howtonode.org/promises

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question