3

Can someone explain to me why the following code returns audiences instead of returning an empty array?

return Audience.find()
  .exec((err, audiences) => {
    if (err) return errorHandler.handle('audienceService', err);

    return Promise.resolve([]);
  });
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Gabriel
  • 741
  • 2
  • 9
  • 18
  • I could explain you just do `return Audience().find()`. You're mixing a "callback" into what you expect to return a `Promise`. The mongoose methods already return promises. – Neil Lunn May 03 '18 at 09:28
  • 1
    @NeilLunn: [That dupetarget](https://stackoverflow.com/questions/43320521/how-to-return-return-from-a-promise-callback-with-fetch) seems like quite a stretch, is there something more directly applicable to using the callback aspect of `exec` rather than the promise aspect? – T.J. Crowder May 03 '18 at 09:33
  • @T.J.Crowder Wrong link in clipboard. Was meant to be the canonical, and was also searching for the lengthy response on mongoose `exec()` which should clear up the additional confusion. Links changed. – Neil Lunn May 03 '18 at 09:39
  • @NeilLunn: :-) I wouldn't say [the async one](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) is a dupetarget for this at all. [The other](https://stackoverflow.com/questions/31549857/mongoose-what-does-the-exec-function-do)'s answers address this tangentially at best, to my mind. – T.J. Crowder May 03 '18 at 09:41

1 Answers1

8

You're returning from the exec callback. To use the promise from exec, use then on it as shown here. There's also no reason for Promise.resolve:

return Audience.find()
  .exec()
  .then(audiences => [])
  .catch(err => errorHandler.handle('audienceService', err));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 2
    This answer doesn't address the question – Neithan Max Oct 16 '18 at 14:46
  • Thank you for this. I've been trying to see how a full implementation of `.then()` `.catch()` with mongoose queries. Is it fine make an async function and await audiences? @t-j-crowder – O'Dane Brissett Sep 20 '19 at 16:03
  • 1
    @O'DaneBrissett - If you have a promise, yes, you can `await` it in an `async` function. So for instance, if it were in an `async` function, the above could be `try { await Audience.find().exec(); return []; } catch (err) { errorHandler.handle('audienceService', err); }`. – T.J. Crowder Sep 20 '19 at 16:06
  • So basically once its async, you can't use `.then()` `.catch()` you have to wrap in a try catch block? @t-j-crowder – O'Dane Brissett Sep 20 '19 at 16:12
  • @O'DaneBrissett - You *can*, it's just usually you don't want to, because the logical flow is usually clearer with the simple flow-control statements that `async` functions let you use instead. – T.J. Crowder Sep 20 '19 at 16:16
  • So it's just not recommended I completed understand. You saved me thanks a lot @t-j-crowder – O'Dane Brissett Sep 20 '19 at 16:21