0

I'm trying to make a function that returns true if it detects a row containing a value in a specific column in nodejs.

I've tried to use the result variable from query() without any success :

let rowexists = (mystring) => {
    let exists = false;
    let sql = "SELECT EXISTS( SELECT 1 FROM mytable WHERE `mycolumn` = '" + mystring + "')";

    connection.query(sql, function(error, result, field){
        console.log((result[sql]));
        console.log(exists);
        exists = (result[sql]);
    });
    return exists;
}

console.log(rowexists("myvalue"));

Event if there is a row with the value "myvalue" (there is), rowexists() always returns false.

IMPORTANT EDIT:

My problem isn't really the fact that this is async, it's the fact that both

console.log((result[sql]));

and

console.log(exists);

return undefined.

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
Telno
  • 53
  • 2
  • 9
  • Possible duplicate of [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) – Heretic Monkey Jun 13 '19 at 15:00
  • it's not only about async response, but ... `result["SELECT EXISTS( SELECT 1 FROM mytable WHERE ``mycolumn`` = '" + mystring + "')"]` ??? also `console.log((result[sql]);` line has a syntax error (brackets are not closed). – Flash Thunder Jun 13 '19 at 15:03
  • `result` is an array of rows so it should be `result[0]` for the first row and `result[0]['mycolumn']` for `mycolumn` in the first row. – Get Off My Lawn Jun 13 '19 at 15:20
  • Not sure why you would want to check existing record what is your goal? iám assuming you want to check before fetching it which means you are running two queries.. – Raymond Nijland Jun 13 '19 at 15:49

1 Answers1

1

A promise is something that is useful in this type of situation.

The issue that you are having, is that your query hasn't finished running by the time the function returns. So, having a promise returned, we can return the value at a later time.

Side Note: You should be using prepared queries when using an SQL database.

let rowexists = (mystring) => {
  // Return a new promise
  return new Promise(resolve => {
    // Create the sql query (this uses placeholders)
    // Hard coded values don't need to be placeholders but just for example:
    let sql = "SELECT 1 FROM ?? WHERE ?? = ?";
    // Query the database replacing the ?? and ? with actual data
    connection.query(sql, ['mytable', 'mycolumn', mystring], function(error, result, field){
      // Result will either be undefined or a row.
      // Convert it to a boolean and return it.
      resolve(!!result)
    });
  });
}

// Get the data
rowexists("myvalue").then(result => console.log(result))

Self invoking function using async/await:

(async function() {
  let exists = await rowexists('myothervalue')
  console.log(exists)
  // The rest of your related code
})()

If you don't like the then() syntax, you can use async/await. Here are two ways in which you can do so:

Basic function using async/await:

async function test() {
  let exists = await rowexists('mythrirdvalue')
  console.log(exists)
  // The rest of your related code
}

test()
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338