0

I am stuck on promise resolution, can anyone explain to me how to store the promise result in a variable? I am working with mongoDB and I want to get some data from it. here is my example.

const checkRelated = new Promise((resolve, reject) => {
     return RelatedProducts.find({
        parent_id: { $in: product_id.split(',') },
      })
        .then((res) => reject(res))
        .catch(err => reject(err))

    })

after getting the data I want to do some validation. For example.

if(checkRelated.length > 0) {
do smth....
}

but to my surprise I get "promise {pending}"

  • why are you creating a new promise? – Dylan L. Apr 11 '22 at 23:15
  • what should I do? – Angry Progy Apr 11 '22 at 23:18
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! What you actually want/need is to put that `if` condition inside the `.then(checkRelated => { … })` callback. – Bergi Apr 12 '22 at 01:16

1 Answers1

2

You're overcomplicating Mongoose, if you want to do an async function you can but I've never seen a new Promise being used with Mongoose. If you want to create an async method with mongoose do the following

exports.getRelatedProducts = async (req, res) => {
  try {
    const checkRelated = await RelatedProducts.find({parent_id: { 
  $in: product_id.split(',') }})

    if (checkRelated.length > 0){
      do smth...
    }
  } catch (error) {
      reject(error)
  }
}

but keep in mind you must create the async method first. then you can use await.

Dylan L.
  • 1,243
  • 2
  • 16
  • 35