Home > Back-end >  JS async function returning undefined although calling it inside an asynchronous function
JS async function returning undefined although calling it inside an asynchronous function

Time:05-01

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.

CodePudding user response:

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.

CodePudding user response:

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]);
        }
      });
  });
}
  • Related