diff --git a/node.js/cds-server.md b/node.js/cds-server.md index 73c9384ac..7060335ba 100644 --- a/node.js/cds-server.md +++ b/node.js/cds-server.md @@ -179,6 +179,7 @@ cds.on('served', (services)=>{ }) ``` +This event supports _asynchronous_ event handlers. ### listening {.event} @@ -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 +#### 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...