i use when.js as a promise library for mongoose and try to get distinct filed of collection and return result as promise
mongoose.Promise= require("when");
function getPromisedDistinct(startDate, endDate) {
return when.promise(function(resolve, reject) {
$log.distinct("keys", {
datetime: {
"$gte": startDate,
"$lt": endDate
}
}).exec()
.then(function(res) {
return resolve(res);
});
});
}
however getPromisedDistinct is resolved with promise function
function (resolve, reject) {
if (!_this.op) {
callback && callback(null, undefined);
resolve();
return;
}
_this[_this.op].call(_this, function(error, res) {
if (error) {
callback && callback(error);
reject(error);
return;
}
callback && callback.apply(null, arguments);
resolve(res);
});
}
edit #1 getPromisedDistinct is called as
function agg(day, startDate, endDate) {
return when.promise(function(resolve, reject) {
getPromisedDistinct(startDate, endDate).then(function(keys) {
log.data("keys is : \n" + licence_keys);
}).otherwise(function(keys) {
return reject(err);
});
});
}
why this not resolved to value?
You've instructed Mongoose to use when.js for its Promise library. If this works as it does with native promises (and seemingly bluebird and q) you don't need to wrap queries in a promise, mongoose will do that for you (once you use
exec()
) so your code could be written as such:You can do the same with your
agg
function.As @robertklep pointed out in the comments there is no need to include a
then
block ingetPromisedDistinct
because it's unnecessary clutter (see promise anti-patterns. You are already returning the promise object withreturn $log.distinct...
and then accessing that value in youragg
function.It's worth taking note of Mongoose's documentation on plugging in a promises library: