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}"
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.