0

I am getting stuck on a Mongoose function. The goal of the function is to:

  1. Store DB query in the query variable
  2. Return True IF there is a DB query matching my criteria. False, otherwise.

The code looks something like:

let query = function (query) {
  return new Promise((res, rej) => {
    res(UserModel.findOne({ username: toString(query) }));
  })
    .then((user) => {
      return user;
    })
    .catch((rej) => {
      console.log(rej);
    });
};
let result = await query(usernameToQuery);
if (result == null) {
  return true;
} else {
  return false;
}

No matter what I do, this code will never return after the query statement has been resolved. All it ever returns to the calling function is promise <pending>. How would I fix this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ken
  • 23
  • 2
  • 3
    [What is the explicit promise construction antipattern and how do I avoid it?](https://stackoverflow.com/q/23803743) | [Is ".then(function(a){ return a; })" a no-op for promises?](https://stackoverflow.com/q/41089122) – VLAZ Jan 12 '22 at 15:44
  • 2
    You trimmed off the top of your code, but presumably you are asking why a function defined as `async` that has `return true` in it returns a promise. See [this question](https://stackoverflow.com/questions/43422932/async-await-always-returns-promise). – Quentin Jan 12 '22 at 15:47
  • That code (which appears to be inside an `async` function) could literally be: `return await UserModel.findOne({username: usernameToQuery}) === null;` (Or you could even drop the `await` in some cases, but it helps with stack traces in environments that have good `async` stack traces, and it would be important to keep it if this code isn't at the top level of the function [for instance, if it's in a `try`/`catch`].) `findOne` returns a [`Query`](https://mongoosejs.com/docs/api/query.html) which is a [*thenable*](https://promisesaplus.com/#point-7). – T.J. Crowder Jan 12 '22 at 15:50
  • Hmmm. That post helps - I guess I am just struggling to wrap my head around the idea that an async function will ONLY return values to other async functions with the 'await' keyword. – Ken Jan 12 '22 at 15:59

0 Answers0