UNPKG

@fbltd/async

Version:

Miscellaneous async utils

52 lines (51 loc) 1.43 kB
import { PromiseConfiguration } from "../promise-configuration.js"; import { symAI } from "../constants.js"; export class DependencyStream { owner; abortPromise = new PromiseConfiguration(); iterator; get isDisposed() { return this.iterator.isDisposed; } get done() { return this.owner.done || !this.abortPromise?.isPending; } constructor(owner) { this.owner = owner; this.abortPromise = new PromiseConfiguration(); this.iterator = owner[symAI](); } [symAI]() { const done = { done: true }; return { next: async () => { if (this.done) { this.abort(); return done; } const nextRes = this.iterator.next(); await Promise.race([ this.abortPromise.promise, nextRes, ]); if (this.done) { this.abort(); return done; } this.abortPromise = new PromiseConfiguration(); return nextRes; } }; } abort() { if (this.abortPromise?.isPending) { this.abortPromise.resolve(); this.abortPromise = undefined; } } dispose() { if (this.done) return; this.abort(); } }