1
function doesUserExist(email){
    let sql = `SELECT * FROM USER WHERE email = "${email}"`
    var x = false;


    let exists = connection.query(sql,(error,results,fields)=>{
        if(error) throw error;
        
        if(results === undefined || results.length === 0) x = false;
        else x = true;
    });

    return x;
}

How can I return a value out of callback or is there some other pattern I can use to accomplish same thing? It seems x never gets updated.

sander
  • 1,426
  • 4
  • 19
  • 46
  • Does this answer your question? [node.js async/await using with MySQL](https://stackoverflow.com/questions/44004418/node-js-async-await-using-with-mysql) – silencedogood Jul 28 '21 at 18:46

1 Answers1

1

In order to consume the value elsewhere, the best method is to return a promise containing the initial query, then consume it with an async function. If not, you're pretty much stuck doing all the work inside the callback.

Here's a away to consume a promise with async/await:

function doesUserExist(email){
  let sql = `SELECT * FROM USER WHERE email = "${email}"`

  return new Promise(function(resolve, reject) {
     connection.query(sql,(error,results,fields)=>{
        if (error) reject(error);
        resolve(results);
     });
  }
 }

Then you could consume it with an async function like so:

async function consumeValue() {
  let results = await doesUserExist(email);

  console.log(results);
  // Do something with results.
}
silencedogood
  • 3,209
  • 1
  • 11
  • 36
  • This is why it's so hard to learn javascript.. it's such an odd creature. Thank you. – sander Jul 28 '21 at 18:02
  • @sander Actually, I misunderstood the question and gave a poor answer. I'm editing now for a proper solution. – silencedogood Jul 28 '21 at 18:12
  • Updated code works like a charm, thanks! Kind of difficult to know when to use Promises and when not.. but I guess that'll come clearer over time. – sander Jul 29 '21 at 03:16