LearnBoost/express-mongoose — Issue #7: How to add intermediary callback
Author: newleafdigital
Created: 2012-01-16 21:05:50+00:00
State: open

I'd like to run a `find` query, then run the results through a custom sort function, then pass them back to my jade templates. I can't seem to get the sort function to affect the results, however.

This is the initial code without the sort function:

```ListSchema.statics.getLists = function(query, callback) {
var promise = new Promise;
if (callback) promise.addBack(callback);

this.find(query, promise.resolve.bind(promise));
return promise;
};

ListSchema.statics.getListsCreatedByUser = function(userId, callback) {
return this.getLists({ _creator: userId }, callback);
});
```

That works fine. If I try to intercept with a new callback, including the sort function, it fails:

```ListSchema.statics.getListsCreatedByUser = function(userId, listIdAtTop, callback) {
return this.getLists(
{ _creator: userId },
function(error, lists) {
if (!error && lists && listIdAtTop) lists = sortListsWithTopId(lists, listIdAtTop); // THIS IS SORTING THE LIST CORRECTLY, BUT DOES NOT PASS THROUGH TO THE VIEW

if (typeof callback == 'function') callback(error, lists);
}
);
}```

`callback` in `getListsCreatedByUser` is in fact undefined, so I'm not sure how it's supposed to work. I don't really understand the Promise syntax. Could you advise?
Thank you!