JavaScript: resolve next event as a promise

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



JavaScript: resolve next event as a promise



For the purpose of testing, I want somehow to wrap events into promises(it's easier to wait for a promise resolution in mocha). So, I write something like:


const collectEvents = (eventEmmiter, eventName, count=1) =>
return new Promise((resolve) =>
const result =
const listener = (msg) =>
result.push(msg)
if(result.length === count)
resolve(result)
eventEmmiter.removeListener(eventName, listener)


eventEmmiter.on(eventName, listener)
)



and use it like this:


Promise.all([
collectEvents(client1, 'message'),
collectEvents(client2, 'message')
]).then(



it works, but I feel like I invented the wheel again. Did I? is there a standard way to achieve the behavior?





I would add an eventEmitter.on("error", reject) (and the respective removeListener) but apart from that it looks totally fine. No, the standard library doesn't provide such a utility yet afaik.
– Bergi
Aug 9 at 13:52


eventEmitter.on("error", reject)


removeListener





in this particular case, a client provides an "error" event; But there is no specification about the "error" event in general.
– kharandziuk
Aug 9 at 14:26





True, although all standard streams I've seen so far provide an error event. Sure, it's not codified, and that's why there is no standard promisification utility either - everyone needs it to behave a little differently. Consider also the case that the stream ends before emitting count events - would you want to reject then?
– Bergi
Aug 9 at 15:00


count





>would you want to reject then? it's also a kinda question which I don't want to answer:) I use the function for testing. So, I rely on mocha timeouts in the case
– kharandziuk
Aug 9 at 15:17









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered