Skip to content

Commit e35fc63

Browse files
authored
Merge pull request #14514 from Automattic/vkarpov15/gh-14305
Add documentation for calling `schema.post()` with async function
2 parents e359b99 + bac8fb0 commit e35fc63

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

docs/middleware.md

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ schema.pre('save', function() {
151151
then(() => doMoreStuff());
152152
});
153153

154-
// Or, in Node.js >= 7.6.0:
154+
// Or, using async functions
155155
schema.pre('save', async function() {
156156
await doStuff();
157157
await doMoreStuff();
@@ -250,9 +250,7 @@ schema.post('deleteOne', function(doc) {
250250

251251
<h2 id="post-async"><a href="#post-async">Asynchronous Post Hooks</a></h2>
252252

253-
If your post hook function takes at least 2 parameters, mongoose will
254-
assume the second parameter is a `next()` function that you will call to
255-
trigger the next middleware in the sequence.
253+
If your post hook function takes at least 2 parameters, mongoose will assume the second parameter is a `next()` function that you will call to trigger the next middleware in the sequence.
256254

257255
```javascript
258256
// Takes 2 parameters: this is an asynchronous post hook
@@ -271,6 +269,25 @@ schema.post('save', function(doc, next) {
271269
});
272270
```
273271

272+
You can also pass an async function to `post()`.
273+
If you pass an async function that takes at least 2 parameters, you are still responsible for calling `next()`.
274+
However, you can also pass in an async function that takes less than 2 parameters, and Mongoose will wait for the promise to resolve.
275+
276+
```javascript
277+
schema.post('save', async function(doc) {
278+
await new Promise(resolve => setTimeout(resolve, 1000));
279+
console.log('post1');
280+
// If less than 2 parameters, no need to call `next()`
281+
});
282+
283+
schema.post('save', async function(doc, next) {
284+
await new Promise(resolve => setTimeout(resolve, 1000));
285+
console.log('post1');
286+
// If there's a `next` parameter, you need to call `next()`.
287+
next();
288+
});
289+
```
290+
274291
<h2 id="defining"><a href="#defining">Define Middleware Before Compiling Models</a></h2>
275292

276293
Calling `pre()` or `post()` after [compiling a model](models.html#compiling)

test/types/middleware.test.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ schema.post<ITest>('save', function() {
6363
console.log(this.name);
6464
});
6565

66+
schema.post<ITest>('save', async function() {
67+
console.log(this.name);
68+
});
69+
6670
schema.post<ITest>('save', function(err: Error, res: ITest, next: Function) {
6771
console.log(this.name, err.stack);
6872
});

0 commit comments

Comments
 (0)