Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I like the async await syntax, and I use it a lot with mongoose.

So in my project there is plenty of :

const user = await User.findOne({
    _id: req.params.id

Which works just as expected. However, in sonarqube, I have these errors : Refactor this redundant 'await' on a non-promise.

And the sonarqube rule i :

It is possible to use await on values which are not Promises, but it's useless and misleading. The point of await is to pause execution until the Promise's asynchronous code has run to completion. With anything other than a Promise, there's nothing to wait for.

This rule raises an issue when an awaited value is guaranteed not to be a Promise.

Noncompliant Code Example

let x = 42;
await x; // Noncompliant
  

Compliant Solution

let x = new Promise(resolve => resolve(42));
await x;
let y = p ? 42 : new Promise(resolve => resolve(42));
await y;

I am using mongo 4.0 and mongoose 5.3.1

Since I can use the .then, .catch syntax I thought that I was dealing with promise so how could I fix that ?

The problem may be in how sonarqube is duck-typing the Query type. From mongoose's own docs "Mongoose queries are not promises", however they are .then()able and are compliant with async/await so you may be getting a false positive. – zero298 Apr 30, 2019 at 18:53 Not sure. But use .exec with the above query and see what happens.const user = await User.findOne({ _id: req.params.id }).exec() Because mongoose queries are not full-fledged promises and .exec help to make it real promise. – Ashh Apr 30, 2019 at 19:43 @Fanpark by the way your solution fixed my issue so if you mind posting it as an answer I'll accept it – L. Faros Jun 5, 2019 at 9:21

I do not know much about SonarQube. I just figured out SonarQube is tool to check the code quality and get that it required await only prefix with the promises and there mongoose fails even having .then.

Mongoose queries do not return "fully-fledged" promise even they have .then(). So in order to get "fully-fledged" promise you need to use .exec() function.

const user = await User.findOne({ _id: req.params.id }).exec()

As mentioned in the comments its a false positive, more accurately a depricated warning.

You can either ignore it or add this to your code right after the import statement:

mongoose.Promise = Promise; 
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.