From ab6961911ba3b66e15705e957df3f6a5c46c698d Mon Sep 17 00:00:00 2001 From: Yuriy Yakym Date: Sun, 17 Dec 2023 23:58:20 +0700 Subject: [PATCH] Update AwaiEvent docs page --- docs/docs/awai-event.md | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/docs/docs/awai-event.md b/docs/docs/awai-event.md index b0d7dd4..11b19bb 100644 --- a/docs/docs/awai-event.md +++ b/docs/docs/awai-event.md @@ -7,7 +7,15 @@ slug: /awai-event Awai event is a promise-like object which has no terminal state and may resolve multiple times. It plays role of event-emitter. -### Example of usage +### Methods + +- **abortable** - method that receives AbortController instance and returns Promise which can be aborted using that controller. It is mainly introduced for internal usage, in order to free memory up as soon as possible +- **emit** - method to emit an event to all the awaiters +- **filter** - method that returns a Promise of an event for which predicate returns truthy value. + +### Examples + +#### Simple usage ```ts title="Example of AwaiEvent usage" const event = new AwaiEvent(); @@ -25,10 +33,10 @@ Notice how we can await the `event` object multiple times and receive different :::note Hint - AwaiEvent is promise-like, hence may be combined with other promise-like objects using Promise methods like `race`, `all` or used in any async function. +AwaiEvent is promise-like, hence may be combined with other promise-like objects using Promise methods like `race`, `all` or used in any async function. ::: -### Example of replacing event-emitter with re-resolvable +#### Replacing event-emitter with re-resolvable In the very traditional approach you would attach event listener like this: @@ -37,7 +45,7 @@ const eventHandler = (event) => /* handle event */; document.addEventListener('click', eventHandler); ``` -The same functionality may be achieved by the following code: +With AwaiEvent, you can write same functionality using async flow. Of course, at some places you would need to attach native events and proxy them to AwaiEvent, but then you can build whole app architecture using Awai approach. ```ts title="AwaiEvent way of listening to events" const clickEvent = new AwaiEvent(); @@ -47,3 +55,26 @@ while (true) { /* handle event */ } ``` + +The above snippet is only written for demonstration purposes. You should use [Scenario](/scenario) instead. + +```ts title="AwaiEvent way of listening to events using Scenario" +const clickEvent = new AwaiEvent(); + +scenario(clickEventReResolvable, (event) => { + /* handle event */ +}); +``` + +#### Filter out events + +```ts title="Handle Enter key only" +const keyDownEvent = new AwaiEvent(); + +scenario( + () => keyDownEvent.filter(event => event.key === 'Enter'), + (event) => { + /* handle event */ + }, +); +```