Home > other >  Why does await/async not work properly when I pass a function into .exec()?
Why does await/async not work properly when I pass a function into .exec()?

Time:08-18

I'm trying to use await to wait for a database lookup using mongoose and save the response to a variable. For some reason, when I pass a function to .exec(), then await doesn't seem to work.

Way that doesn't work:

    var document = await Collection.findOne({ 'num': num }).populate('field').exec((err, result) => {
            if (err) throw error
    })
    console.log(document) // undefined

Way that does work:

    var document = await Collection.findOne({ 'num': num }).populate('field').exec()
    console.log(document) // The document I want

I don't think the population is what is causing the problem because I tried the code without the population and it worked. Why does this happen and how can I fix this?

CodePudding user response:

This is the documented behaviour of mongodb:

NOTE
If you specify a callback, the method does not return a Promise.

(Emphasis theirs)

Also here:

NOTE: All the examples below use async/await syntax.

However, all async API calls support an optional callback as the final argument, if a callback is provided a Promise will not be returned.

  • Related