0

Here's my code

function getprefix(guildid) {
    con.connect(function(err) {
        con.query('SELECT * from ' + configcontent.guilds_table_name + ' WHERE guild_id=' + String(guildid), function(err, result) {
            if (err) {
                throw err;
            } else {
                return result[0].prefix;
            }
        });
    });
}

I wanted to make this function to return one value from one column (from first result), but it returns undefined. When i tried to write it on screen (using console.log(result[0].prefix);) it works. Please help. Sorry for bad description or english. Its my first question on StackOverflow

2 Answers 2

1

Your function is asynchronous, so it immediately returns result, now it returns undefined. Value from DB returned later, and passed to callback. You need to use promises(preferred)/callbacks to return async results from your function, something like this:

function getprefix(guildid) {
      return new Promise((resolve, reject) => {
        con.connect(function (err) {
          con.query('SELECT * from ' + configcontent.guilds_table_name + ' WHERE guild_id=' + String(guildid), function (err, result) {
            if (err) {
              // throw err;
              // instead of throwing we passing error to result promise
              reject(err)
            } else {
              // return result[0].prefix;
              // instead of return we pass result to promise
              resolve(result[0].prefix)
            }
          });
        });
      }
    }

so usage will look like:

getprefix(guildid)
  .then(prefix => console.log(prefix))
  .catch(e => console.err('Unable to get prefix', e))

it would be great to check the different ways to handle async programming in JS with callbacks/promises/async awaits in details.

Sign up to request clarification or add additional context in comments.

2 Comments

But the question is how to use promise to assign value to variable? Should i replace console.log(prefix) with this or what else?
@Mruczacy could you show us how you use getprefix in your applicatio? i see you dont know exactly how promises work in JS
0

You can't return value from a callback.

Before you make your query, connect to the db. Don't use the callback function for that, cuz making a query supposed to be made with con.query

function getprefix(guildid) {
    con.connect();
    con.query('SELECT * from ' + configcontent.guilds_table_name + ' WHERE guild_id=' + String(guildid), function(err, result) {
        if (err) {
           throw err;
        } else {
           // do stuff with 'results'
        }
    });

EDIT

You can use async/await like this to get access to the return value, but you have to wrap your code in an IIFE (Immediately Invoked Function Expression) or use top level await, but it's only available in the latest version of Node.

Note, that I only used IIFE, because I don't have any other function or logic where I could call my query. If you call it in another function, make it async.

// Top level action
(async () => {
  const output = await makeQuery();
  console.log(output);
})();

// Query
function makeQuery() {
  return new Promise((resolve, reject) =>
    db.query("SELECT * FROM users", (err, res) => {
      if (err) reject(err);
      else resolve(res);
    })
  );
}

3 Comments

I tried your way in returning value but it doesn't works. It still returns undefined
Why do you think it won't work? I tested it and it works perfectly.
Nevermind, I just realized what you were refering to. :D I'm gonna remove that part

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.