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

Fix onNext #44

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
8 changes: 4 additions & 4 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -645,8 +645,8 @@ export class RealtimeClient extends RealtimeEventHandler {
* Utility for waiting for the next `conversation.item.appended` event to be triggered by the server
* @returns {Promise<{item: ItemType}>}
*/
async waitForNextItem() {
const event = await this.waitForNext('conversation.item.appended');
async waitForNextItem(timeout = null) {
const event = await this.waitForNext('conversation.item.appended', timeout);
const { item } = event;
return { item };
}
Expand All @@ -655,8 +655,8 @@ export class RealtimeClient extends RealtimeEventHandler {
* Utility for waiting for the next `conversation.item.completed` event to be triggered by the server
* @returns {Promise<{item: ItemType}>}
*/
async waitForNextCompletedItem() {
const event = await this.waitForNext('conversation.item.completed');
async waitForNextCompletedItem(timeout = null) {
const event = await this.waitForNext('conversation.item.completed', timeout);
const { item } = event;
return { item };
}
Expand Down
23 changes: 10 additions & 13 deletions lib/event_handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,12 @@ export class RealtimeEventHandler {
*/
onNext(eventName, callback) {
this.nextEventHandlers[eventName] = this.nextEventHandlers[eventName] || [];
this.nextEventHandlers[eventName].push(callback);
return callback;
const listener = event => {
this.off(eventName, listener);
callback(event);
}
this.nextEventHandlers[eventName].push(listner);
return listener;
}

/**
Expand Down Expand Up @@ -107,19 +111,12 @@ export class RealtimeEventHandler {
* @returns {Promise<{[key: string]: any}|null>}
*/
async waitForNext(eventName, timeout = null) {
const t0 = Date.now();
let nextEvent;
this.onNext(eventName, (event) => (nextEvent = event));
while (!nextEvent) {
return new Promise((resolve, reject) => {
this.onNext(eventName, resolve);
if (timeout) {
const t1 = Date.now();
if (t1 - t0 > timeout) {
return null;
}
setTimeout(() => reject(new Error(`Timeout waiting for "${eventName}"`)), timeout);
}
await sleep(1);
}
return nextEvent;
});
}

/**
Expand Down