Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to store mysql query result inside a variable #2458

Closed
mikias21 opened this issue Jan 20, 2021 · 3 comments
Closed

Unable to store mysql query result inside a variable #2458

mikias21 opened this issue Jan 20, 2021 · 3 comments
Labels

Comments

@mikias21
Copy link

mikias21 commented Jan 20, 2021

I am trying to query user by email and save the result inside a variable. I tried using await and async, callback and promise but
none of them actually work.

const checkEmailUsed = (email) => {
  let sql = "SELECT * FROM users_signup WHERE user_email = ? LIMIT 1";
  return new Promise((resolve, reject) => {
    conn.query(sql, email, (err, res) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(res[0]);
    });
    conn.end();
  });
};

var user = [];
checkEmailUsed("mikias@email.com")
  .then((res) => user.push(res))
  .catch((err) => console.log(err));

console.log(user); // Still []
@mbaumgartl
Copy link

The console.log is executed before the promise is fulfilled. This should work:

const checkEmailUsed = (email) => {
  let sql = "SELECT * FROM users_signup WHERE user_email = ? LIMIT 1";
  return new Promise((resolve, reject) => {
    conn.query(sql, email, (err, res) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(res[0]);
    });
    conn.end();
  });
};

var user = [];
checkEmailUsed("mikias@email.com")
  .then((res) => user.push(res))
  .then(() => console.log(user))
  .catch((err) => console.log(err));

@mikias21
Copy link
Author

mikias21 commented Jan 21, 2021 via email

@Zikoel
Copy link

Zikoel commented Apr 13, 2021

@mikias21 can you mark this issue as closed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

4 participants