0

I'm using a variable inside the nested function and after assigning a value pass to the parent function but on calling it shows nothing.

function userexists(key) {
  let user = false;
  UsersModel.findOne({ email: key }, function (error, foundUser) {
    if (!error && foundUser) user = foundUser;
    else {
      console.log("error or not found: " + error);
    }
  });

  return user;
}
SEJ
  • 31
  • 6
  • 1
    The reason for that is that `findOne` seems to be an async function. Therefore `user` is always false. Make sure to `async await` or a callback function in the function itself. – FloWy Mar 05 '21 at 14:05
  • so in this situation, what should I suppose to do? – SEJ Mar 05 '21 at 14:08
  • [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) – VLAZ Mar 05 '21 at 14:09

2 Answers2

0

The reason for that is that findOne seems to be an async function. Therefore user is always false. Make sure to async await or add a callback function in the function itself.

Example async await, if possible:

async function abc(key) {
  const response = await UsersModel.findOne({ email: key });
  if (response.error)
    return false;
  }

  return response.foundUser;
}

Example callback function:

function async abc(key, f) {
  UsersModel.findOne({ email: key }, (error, foundUser) => {
    if (!error) f();
  });
}
FloWy
  • 934
  • 6
  • 14
0

Thanks to FloWy and VLAZ

Before,

function userexists(key) {
  let user = false;
  UsersModel.findOne({ email: key }, function (error, foundUser) {
    if (!error && foundUser) user = foundUser;
    else {
      console.log("error or not found: " + error);
    }
  });

  return user;
}

Using callback inside a function,

function userexists(key, callback) {
  UsersModel.findOne({ email: key }, function (error, foundUser) {
    if (!error && foundUser) return callback(foundUser);
    else return callback(false);
  });
}

On Call,

userexists(username, function (user) {
// you can use user here
});
SEJ
  • 31
  • 6