Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Asynchronous event handlers for served and shutdown #380

Merged
merged 1 commit into from
Sep 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions node.js/cds-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ cds.on('served', (services)=>{
})
```

This event supports _asynchronous_ event handlers.


### listening {.event}
Expand All @@ -191,10 +192,36 @@ A one-time event, emitted when the server has been started and is listening to i

A one-time event, emitted when the server is closed and/or the process finishes. Listeners can execute cleanup tasks.

This event supports _asynchronous_ event handlers.


### Event Handlers
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this be a level two header? And could both headers be one line? Like: Sync vs. Async Event Handlers or Event Handler: Sync/Async


#### Synchronous vs. asynchronous

Unless otherwise noted, event handlers execute **synchronously** in the order they are registered.
This is due to `cds.on()` and `cds.emit()` using Node's [EventEmitter](https://nodejs.org/api/events.html#asynchronous-vs-synchronous) contract.

In other words this asynchronous handler code does **not work** as expected:

```js
cds.on ('bootstrap', async ()=> {
await asyncCode() // [!code error] // will NOT be awaited
}
```

You can use the [served](#served) event's asynchronous nature though to wait for such bootstrap code:

```js
let done
cds.on('bootstrap', ()=> {
done = asyncCode()
}
cds.on('served', async ()=> {
await moreCode()
await done
})
```


## See Also...
Expand Down