Skip to content

Commit

Permalink
docs(middleware): add note about using async functions for post hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Apr 9, 2024
1 parent e359b99 commit 7629c94
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions docs/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,9 +250,7 @@ schema.post('deleteOne', function(doc) {

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

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.
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.

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

You can also pass an async function to `post()`.
If you pass an async function that takes at least 2 parameters, you are still responsible for calling `next()`.
However, you can also pass in an async function that takes less than 2 parameters, and Mongoose will wait for the promise to resolve.

```javascript
schema.post('save', async function(doc) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('post1');
// If less than 2 parameters, no need to call `next()`
});

schema.post('save', async function(doc, next) {
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('post1');
// If there's a `next` parameter, you need to call `next()`.
next();
});
```

<h2 id="defining"><a href="#defining">Define Middleware Before Compiling Models</a></h2>

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

0 comments on commit 7629c94

Please sign in to comment.