event-as-promise
Handle continuous stream of events with Promise and generator function.
There are multiple alternatives, for example, p-event is a popular choice.
Instead of listen to event just once, event-as-promise
chose an approach to allow listening to the same event continuously. And we use generator function to enable for(of)
loop to handle event indefinitely.
How to use
Web server
This sample code is converted from Node about page.
;; { const server = http; const listeningPromises = ; const requestPromises = array: true ; server ; // Wait for "listening" await listeningPromises; // Loop indefinitely, using generator for let requestPromise of requestPromises // Wait for "request" const req res = await requestPromise; resstatusCode = 200; res; res; } ;
Note: as multiple results is not supported by Promise, the
array
option will group multiple event arguments into an array. By default, it isfalse
.
Redux Saga
Handling event in a Promise may not reduce complexity. But it will be beneficial for redux-saga
when mixed with call
effect.
In this example, when the user is connected via CONNECTED
action, we will keep the user posted about file changes, until a DISCONNECTED
is received.
saga;
Futures
You can retrieve multiple Promise objects before the event is emitted.
const emitter = ;const countPromises = ; emitter; // Retrieve multiple future Promise before the actual event is firedconst promise1 = countPromises;const promise2 = countPromises;const promise3 = countPromises; emitter;emitter;emitter; await resolves;await resolves;await resolves;
Same as event listener, if
one()
is not called before the event is emitted, the event will be lost.
Upcomings
Instead of futures, you can use upcoming()
to get the Promise for the upcoming event. Futures and upcoming Promises are independent of each other, as shown in the sample below.
const emitter = ;const countPromises = ; emitter; const promiseOne1 = countPromises;const promiseOne2 = countPromises;const promiseOne3 = countPromises;const promiseTwo = countPromises; emitter;emitter; await resolves;await resolves;await resolves;await resolves; const promiseThree = countPromises; emitter; await resolves;await resolves;
Note: after the current
upcoming()
has resolved, you will need to callupcoming()
again to obtain a new Promise for the next upcoming event.
Contributions
Like us? Star us.
Want to make it better? File us an issue.
Don't like something you see? Submit a pull request.