So, I have a piece of code that makes use of Promises
and I am using the bluebird
library.
The problem is that my promise gets rejected even if there is no error. It completely skips the .then
block even for a simple console.log
Here is the code that makes use of promise:
function returnMeetings(query) {
return new Promise((reject, resolve) => {
Meeting.find(query, (err, foundMeetings) => {
if (err) {
console.log("We have a error")
reject(err);
}
resolve(foundMeetings);
})
})
}
And here is the code that makes use of that returnMeetings
function
returnMeetings(query)
.then((data) => {
console.log("here we are")
// while (count < stopAt) {
// let localData = [];
// if (req.params.duration === 'monthly') {
// let {
// date1,
// date2
// } = twoDates(count, count);
// localData = data.filter((el) => {
// if (el.startDate) {
// let localDate = new Date(el.startDate);
// if (localDate >= date1 && localDate <= date2) {
// return el;
// }
// }
// })
// if (localData) {
// data.push({
// data: localData,
// month: count
// })
// }
//
// if (count === stopAt - 1) {
// myEmitter.emit('found all meetings')
// } else {
// count++;
// }
// }
// }
}).catch((err) => {
res.status(500).json({
message: err
})
})
As you can see in the returnMeetings
function i have placed a console.log
inside the if(err)
block, and it never runs, from that I conclude that I didn't receive any error from the mongoose query.
Still, the code completely skips the .then
block, and falls into the catch
chain. I have a simple console.log
inside the then
block, and an interesting thing to note is that the value of err
in the callback inside catch
block is an array of mongodb documents.
Can someone explain, why is my code behaving in this manner?
Thanks for your help.
the order of resolve/reject in your Promise constructor callback is wrong ... the names of the functions are irrelevant, the first is to resolve, the second is to reject ... you are actually rejecting the promise when you call resolve
i.e. you could
return new Promise((fred, wilma) => {
then to resolve the promise, you would call fred(value)
and to reject you would call wilma(error)
in other words, the names you give the callback arguments is irrelevant, the position is relevant
change your code as follows:
function returnMeetings(query) {
return new Promise((resolve, reject) => {
Meeting.find(query, (err, foundMeetings) => {
if (err) {
console.log("We have a error")
reject(err);
}
resolve(foundMeetings);
})
})
}