Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a queue for triggered events before using one() #4

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import createDeferred from './external/p-defer';

export default class EventAsPromise {
constructor(options = {}) {
this.queue = [];
this.defers = [];
this.upcomingDeferred = null;
this.eventListener = this.eventListener.bind(this);
Expand All @@ -22,7 +23,13 @@ export default class EventAsPromise {
const deferred = this.defers.shift();
const args = this.options.array ? [].slice.call(arguments) : event;

deferred && deferred.resolve(args);
if (deferred) {
deferred.resolve(args);
} else if (this.options.queue) {
const newDeferred = createDeferred();
newDeferred.resolve(args);
this.queue.push(newDeferred.promise);
}

if (this.upcomingDeferred) {
this.upcomingDeferred.resolve(args);
Expand All @@ -31,6 +38,10 @@ export default class EventAsPromise {
}

one() {
if (this.options.queue && this.queue.length > 0) {
return this.queue.shift();
}

const deferred = createDeferred();

this.defers.push(deferred);
Expand Down
23 changes: 23 additions & 0 deletions src/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,29 @@ test('no backlog', async () => {
await expect(upcomingPromise).resolves.toBe(2);
});

test('with backlog', async () => {
const eventAsPromise = new EventAsPromise({ queue: true });
const emitter = new EventEmitter();

emitter.on('count', eventAsPromise.eventListener);
emitter.emit('count', 1);

const promise1 = eventAsPromise.one();
const promise2 = eventAsPromise.one();
const upcomingPromise = eventAsPromise.upcoming();

emitter.emit('count', 2);

await expect(hasResolved(promise1)).resolves.toBeTruthy();
await expect(promise1).resolves.toBe(1);

await expect(hasResolved(promise2)).resolves.toBeTruthy();
await expect(promise2).resolves.toBe(2);

await expect(hasResolved(upcomingPromise)).resolves.toBeTruthy();
await expect(upcomingPromise).resolves.toBe(2);
});

test('repeated', async () => {
const eventAsPromise = new EventAsPromise();
const emitter = new EventEmitter();
Expand Down