mysqljs / mysql

A pure node.js JavaScript Client implementing the MySQL protocol.
MIT License
18.28k stars 2.52k forks source link

Unable to store mysql query result inside a variable #2458

Closed mikias21 closed 3 years ago

mikias21 commented 3 years ago

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 commented 3 years ago

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 commented 3 years ago

Thank you very much sir. Thank you

On Thu, Jan 21, 2021 at 2:11 AM Marco Baumgartl notifications@github.com wrote:

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));

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/mysqljs/mysql/issues/2458#issuecomment-764527349, or unsubscribe https://github.com/notifications/unsubscribe-auth/AJOBECIEMRMZS6W3UXHUGPDS274URANCNFSM4WKFMN4A .

Zikoel commented 3 years ago

@mikias21 can you mark this issue as closed?