UNPKG

@genkit-ai/core

Version:

Genkit AI framework core libraries.

104 lines 2.1 kB
function createTask() { let resolve, reject; const promise = new Promise( (res, rej) => [resolve, reject] = [res, rej] ); return { resolve, reject, promise }; } class Channel { ready = createTask(); buffer = []; err = null; send(value) { this.buffer.push(value); this.ready.resolve(); } close() { this.buffer.push(null); this.ready.resolve(); } error(err) { this.err = err; this.ready.reject(err); } [Symbol.asyncIterator]() { return { next: async () => { if (this.err) { throw this.err; } if (!this.buffer.length) { await this.ready.promise; } const value = this.buffer.shift(); if (!this.buffer.length) { this.ready = createTask(); } return { value, done: !value }; } }; } } class LazyPromise { executor; promise; constructor(executor) { this.executor = executor; } then(onfulfilled, onrejected) { this.promise ??= new Promise(this.executor); return this.promise.then(onfulfilled, onrejected); } } function lazy(fn) { return new LazyPromise((resolve, reject) => { try { resolve(fn()); } catch (e) { reject(e); } }); } class AsyncTaskQueue { last = Promise.resolve(); options; constructor(options) { this.options = options || {}; } /** * Adds a task to the queue. * The task will be executed when its turn comes up in the queue. * @param task A function that returns a value or a PromiseLike. */ enqueue(task) { if (this.options.stopOnError) { this.last = this.last.then(() => lazy(task)).then((res) => res); } else { this.last = this.last.catch(() => { }).then(() => lazy(task)).then((res) => res); } this.last.catch(() => { }); } /** * Waits for all tasks currently in the queue to complete. */ async merge() { await this.last; } } export { AsyncTaskQueue, Channel, LazyPromise, createTask, lazy }; //# sourceMappingURL=async.mjs.map