2

I am using nodeJs Express and I have an async function which is used in another function.

here is my code:

/* get user info */
const getUserInfo = async (req) => {
    let userID = req.cookies.userId;
    if(!userID) return null;
    await connection.query('SELECT * FROM users WHERE id = ' + userID,
        function (err, rows, fields) {
            if (err) throw err
            // if user not found
            if (rows.length === 0) {
                return null;
            }
            // if user found
            else {
                return rows[0];
            }
        });
}
/* display dashboard page */
router.get("/", async function (req, res, next) {
    let userInfo = await getUserInfo(req);

    console.log(userInfo) // It's result is undefined


    if (userInfo) {
        res.render('dashboard/profile', {
            fullName: userInfo.fname + " " + userInfo.lname,
            email: userInfo.email,
            phone: userInfo.phone,
        });
    }
    else {
        res.render('authentication/register', {
            title: 'ثبت نام',
        });
    }

});

how to resolve this problem? I need userInfo retun me some data.

1
  • connection.query(query, callback) does not return a Promise - async/await is not syntax for using asynchronous callbacks - it's 100% only used for Promises Commented May 1, 2022 at 9:03

2 Answers 2

1

await is only useful if the value on the right-hand side is a promise.

connection.query is taking a callback function, which implies it isn't returning a promise.

You need to either:

  • Find out how to make the API you are using return a promise (if that is possible)
  • Wrap the callback in a promise
  • Replace the API with one that supports promises natively

You also need getUserInfo to have a return statement of its own.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to return some value from your getUserInfo function

If connection query doesn't support promise you should wrap it like this

/* get user info */
const getUserInfo = async(req) => {
  let userID = req.cookies.userId;
  if (!userID) return null;
  return new Promise((resolve, reject) => {
    connection.query('SELECT * FROM users WHERE id = ' + userID,
      function(err, rows, fields) {
        if (err) {
          reject(err)
          return;
        }
        // if user not found
        if (rows.length === 0) {
          resolve(null)
        }
        // if user found
        else {
          resolve(rows[0]);
        }
      });
  });
}

Comments

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.