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.

4
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Jun 13, 2019 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). Commented Jun 13, 2019 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. Commented Jun 13, 2019 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.. Commented Jun 13, 2019 at 15:49

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

I tried your code with promises, and it stays pending
of the three styles I demonstrated, which style did you use?
The first with promises
But that's not really my main problem, I edited my post to clarify

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.