Search code examples
javascriptmongodbmongoosees6-promise

Mongoose find().exec() promise issue


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([]);
  });

Solution

  • 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));