Skip to content

Commit

Permalink
Merge pull request #13509 from Automattic/vkarpov15/aggregate-finally
Browse files Browse the repository at this point in the history
feat(aggregate): add `Aggregate.prototype.finally()` to be consistent with Promise API for TypeScript
  • Loading branch information
vkarpov15 committed Jun 14, 2023
2 parents e8987d0 + e1dae1a commit b6f18fe
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/aggregate.js
Expand Up @@ -1094,7 +1094,7 @@ Aggregate.prototype.then = function(resolve, reject) {
};

/**
* Executes the query returning a `Promise` which will be
* Executes the aggregation returning a `Promise` which will be
* resolved with either the doc(s) or rejected with the error.
* Like [`.then()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.then), but only takes a rejection handler.
* Compatible with `await`.
Expand All @@ -1108,6 +1108,21 @@ Aggregate.prototype.catch = function(reject) {
return this.exec().then(null, reject);
};

/**
* Executes the aggregate returning a `Promise` which will be
* resolved with `.finally()` chained.
*
* More about [Promise `finally()` in JavaScript](https://thecodebarbarian.com/using-promise-finally-in-node-js.html).
*
* @param {Function} [onFinally]
* @return {Promise}
* @api public
*/

Aggregate.prototype.finally = function(onFinally) {
return this.exec().finally(onFinally);
};

/**
* Returns an asyncIterator for use with [`for/await/of` loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js)
* You do not need to call this function explicitly, the JavaScript runtime
Expand Down
9 changes: 9 additions & 0 deletions types/aggregate.d.ts
Expand Up @@ -16,6 +16,9 @@ declare module 'mongoose' {
*/
[Symbol.asyncIterator](): AsyncIterableIterator<Unpacked<ResultType>>;

// Returns a string representation of this aggregation.
[Symbol.toStringTag]: string;

options: AggregateOptions;

/**
Expand Down Expand Up @@ -73,6 +76,12 @@ declare module 'mongoose' {
/** Appends a new $fill operator to this aggregate pipeline */
fill(arg: PipelineStage.Fill['$fill']): this;

/**
* Executes the aggregation returning a `Promise` which will be
* resolved with `.finally()` chained.
*/
finally: Promise<ResultType>['finally'];

/** Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection. */
graphLookup(options: PipelineStage.GraphLookup['$graphLookup']): this;

Expand Down

0 comments on commit b6f18fe

Please sign in to comment.