Skip to content

Commit

Permalink
Rename to AsyncEmitter, implement await once and fix clear
Browse files Browse the repository at this point in the history
  • Loading branch information
tshemsedinov committed Jun 4, 2019
1 parent 6e72852 commit 4102ef3
Show file tree
Hide file tree
Showing 4 changed files with 247 additions and 201 deletions.
33 changes: 25 additions & 8 deletions lib/aee.js → lib/async-emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const { iter } = require('@metarhia/common');

class AsyncEventEmitter {
class AsyncEmitter {
constructor() {
this.events = new Map();
this.wrappers = new Map();
Expand All @@ -18,12 +18,18 @@ class AsyncEventEmitter {
}

once(name, fn) {
if (fn === undefined) {
return new Promise(resolve => {
this.once(name, resolve);
});
}
const wrapper = (...args) => {
this.remove(name, wrapper);
return fn(...args);
};
this.wrappers.set(fn, wrapper);
this.on(name, wrapper);
return undefined;
}

async emit(name, ...args) {
Expand All @@ -35,20 +41,31 @@ class AsyncEventEmitter {
}

remove(name, fn) {
const event = this.events.get(name);
const { events, wrappers } = this;
const event = events.get(name);
if (!event) return;
if (event.has(fn)) event.delete(fn);
const wrapper = this.wrappers.get(fn);
const wrapper = wrappers.get(fn);
if (wrapper) {
this.wrappers.delete(fn);
wrappers.delete(fn);
event.delete(wrapper);
}
if (event.size === 0) this.events.delete(name);
if (event.size === 0) events.delete(name);
}

clear(name) {
if (name) this.events.delete(name);
else this.events.clear();
const { events, wrappers } = this;
if (!name) {
events.clear();
wrappers.clear();
return;
}
const event = events.get(name);
if (!event) return;
for (const [fn, wrapper] of wrappers.entries()) {
if (event.has(wrapper)) wrappers.delete(fn);
}
events.delete(name);
}

count(name) {
Expand All @@ -66,4 +83,4 @@ class AsyncEventEmitter {
}
}

module.exports = { AsyncEventEmitter };
module.exports = { AsyncEmitter };
2 changes: 1 addition & 1 deletion metasync.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const submodules = [
'poolify', // Create pool from factory
'queue', // Concurrent queue
'throttle', // Throttling utilities
'aee', // AsyncEventEmitter
'async-emitter', // AsyncEmitter
].map(path => require('./lib/' + path));

if (nodeVerion >= 10) {
Expand Down
192 changes: 0 additions & 192 deletions test/aee.js

This file was deleted.

Loading

0 comments on commit 4102ef3

Please sign in to comment.