0

I could not return the value from the function, I have no problem with my sql it works fine, I just can't return the result value and pass it to res variable.

io.on('connection', function (socket) {


            socket.on('getdetails', function (data) {

                 var res = getdatatodb(data.id);

                  console.log("result",res);

            });
        });


   });

   function getdatatodb(id){

       connection.connect(function(err) {
                if (err) {
                    console.error('error connecting: ' + err.stack);
                    return;
                }


                var options = {sql: ".....",nestTables: true };
                connection.query(options,function(err, results) {
                    if(err){
                        console.log(err);
                    }

                    return results;
                });
         });
    }

Thank you in advance.

jemz
  • 4,987
  • 18
  • 62
  • 102
  • This is a dup of many other questions. When you return a value form a callback, that value goes back into the engine that called the callback, not returning from the outer function. And, the callback is usually async which means it is called long after the outer function has already finished. – jfriend00 Mar 28 '15 at 06:40
  • so how do i get the result ? – jemz Mar 28 '15 at 06:41
  • possible duplicate of [How does Asynchronous Javascript Execution happen? and when not to use return statement?](http://stackoverflow.com/questions/7104474/how-does-asynchronous-javascript-execution-happen-and-when-not-to-use-return-st) – jfriend00 Mar 28 '15 at 15:58
  • 1
    You don't. You process the result IN the completion callback or call some function from within the callback. You can't return the result from your outer function. You may want to pass a callback function to `getdatatodb()` that you can call when the result is available. You cannot synchronously return data from an async operation. Cannot be done in Javascript. – jfriend00 Mar 28 '15 at 16:00

0 Answers0