0
function status(s) {
    const n = parseInt(s.substr(1));
    var o = '';
    switch(s[0]) {
        case 'c':
            c.query("SELECT * FROM chapters WHERE id='"+n+"' LIMIT 1", function(e, r) {
                if (e) throw e;
                o = r[0].t;
            });
            break;
    };
    return o;
};

console.log(status('c1'));

How to make this returning variable 'o' from function inside query?

Freezend
  • 11
  • 2
  • That's async call to mysql db. you are returning "o" too early even before finishing execution. you see anonymous function within query call that's a call back. You can use promise to resolve "o" for you and wrap it inside async function. – Sagar Jul 25 '20 at 10:34
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Molda Jul 25 '20 at 10:37
  • Okay, I thought it could be solved in some simple way, but it looks complicated so I swapped one request for 2, the first one returns data with that id and the second (sent after the first) converts that id to text from the other table in the database. – Freezend Jul 25 '20 at 10:47

2 Answers2

0

You need to use a Promise. Here is an example. I've also refactored the program flow control to the functional level:

const makeQuery = s => 
    `SELECT * FROM chapters WHERE id='${parseInt(s.substr(1))}' LIMIT 1`

const doQuery = s => new Promise((resolve, reject) => c.query(
               makeQuery(s), 
               (e, r) => e ? reject(e) : resolve(r[0].t)));

const status = s => 
     s[0] === 'c' ? 
        doQuery(s) : 
        Promise.resolve(undefined)

status('c1').then(console.log);

You can do the same thing using async and await, if the query function has a Promise interface in addition to the error-first callback one that you are using at the moment.

Josh Wulf
  • 4,727
  • 2
  • 20
  • 34
0

Okay, thanks a lot. I've rewritten all the code so that it sends two requests, the second one after receiving the data from the first one, and kicked this function out, but it's very possible that I might need to understand this in the future.

Freezend
  • 11
  • 2