0

This piece of code always returns undefined to the calling function. I'm new to JavaScript and I did try and look into some of the callback solutions on Stack Overflow and other resources but none of them worked for me. Any help with this would be highly appreciated. Thank you!

var funcs = require('./index.js');
var connected = require('./database')

query='SELECT * from trades'
const res = execute_rows(query)
console.log(res)


function execute_rows(query){
 con = connected();
 con.query(query, function(err, result, fields) {
     if (err) {
         return console.log(err);
     }
     console.log(result) //Displays correct results
     return result; // Returns undefined to calling function
 })
 con.end();
}
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – pilchard Jan 24 '22 at 15:24
  • I did try to implement this but I couldn't understand nor replicate it. – Harshith Patil Jan 24 '22 at 15:45

1 Answers1

1

Harshith

Ok, if you print de result of your query inside the function execute_rows just before de return statement you should be able to see it.

The problem with your function is your not actually returning the result "on time". You need to return a promise to get the result from your function.

This could be a little hard to understand when you're new in JS. Your function should be something like this:

function execute_rows(query){
 con = connected();
 return new Promise((resolve, reject) => {
     con.query(query, function(err, result, fields) {
         if (err) {
             // Returning the error
             reject(err);
             con.end();
         }

         resolve(result);
         con.end();
     });
 });
}

Now, when you call you call your function, you have two options:

  1. Use async/await
  2. Still using promises (callback-driven)

Calling your function:

const dbResult = await execute_rows(query);

or

execute_rows(query).then(result => {
    // Get the result
    console.log('result:', result);
}).catch(error => {
    // Get the error
    console.log('error:', error);
});

Please, read about promises and async/await pattern! Links:

Promises: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise

Async/await: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

Gutty
  • 36
  • 1
  • 7
  • Hey, I tried your solution and it still does not work. I either get "SyntaxError: await is only valid in async functions and the top level bodies of modules" when I try the first calling method or I get "TypeError: Cannot read properties of undefined (reading 'then') at Object." when I try the second method. – Harshith Patil Jan 24 '22 at 16:47
  • @HarshithPatil I'm sorry, I updated my questions because I had an error in the promise return statement. Now you can try. Your "SyntaxError" based on the async/await solution is because you need to make your higher function asynchronous. Read about async/await to understand that. Try the second way (using then-catch) and let me know! – Gutty Jan 24 '22 at 17:09
  • @Gutty Thanks! this solved a major issue for me. con.query was returning undefined when I didn't have a working example. Thanks again! – Drwooi Poipoi Feb 26 '23 at 21:37