Amel Islamovic
Amel Islamovic

Reputation: 182

Return will return empty object even it shoudn't

here is my code

  (email) => {
    let con = {};
    connection.query(
      "SELECT * FROM users WHERE email=?",
      email,
      (error, result) => {
        con.id = result[0].id;
        con.email = result[0].email;
        con.name = result[0].name;
        con.password = result[0].password;
      }
    );
    return con;
  },

It's simple, it should return con object, but it returns it empty. I think because this query will execute last in function. Any help?

Upvotes: 0

Views: 36

Answers (2)

technophyle
technophyle

Reputation: 9118

You're right, the query will take a bit of time and con will be already returned by the time it finishes running.

Even if it doesn't take any time, the callback function is going to be run separately so con will not be updated either way.

You have two options:

  • use a promise version of the query() method if it's available.
  • promise-ify the query.

This is roughly how you can do it (2nd option):

return new Promise((resolve) => {
  connection.query(
  "SELECT * FROM users WHERE email=?",
  email,
  (error, result) => {
    let con = {};
    con.id = result[0].id;
    con.email = result[0].email;
    con.name = result[0].name;
    con.password = result[0].password;
    resolve(con);
  }
});

...
// and you can use it like this
const result = await myFunc(email);

Upvotes: 0

Anatoly
Anatoly

Reputation: 22758

You can try to turn your function into async and wrap connection.query with new Promise like this:

(email) => {
    return new Promise((resolve, reject) => {
      connection.query(
        "SELECT * FROM users WHERE email=?",
        email,
        (error, result) => {
          if (error) {
            reject(error);
          }
          const con = {};
          con.id = result[0].id;
          con.email = result[0].email;
          con.name = result[0].name;
          con.password = result[0].password;
          resolve(con);
        }
      );
  }

And using it like this:

func(email).then(con => {
  console.log(con)
});

or with await:

const con = await func(email);

Upvotes: 1

Related Questions