Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/util/async-wait.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45/*6Wait until some function until of obj is truthy7(not truthy includes "throw an exception").89Waits until "until(obj)" evaluates to something truthy10in *seconds* -- set to 0 to disable (sort of DANGEROUS, obviously.)11Returns until(obj) on success and raises Error('timeout') or12Error('closed') on failure (closed if obj emits13'closed' event.1415obj is an event emitter, and obj should emit change_event16whenever it changes.1718obj should emit 'close' if it prematurely ends.1920The until function may be async.21The timeout can be 0 to disable timeout.22*/2324import { callback } from "awaiting";2526import { EventEmitter } from "events";2728interface WaitObject extends EventEmitter {29get_state: Function;30}3132export async function wait({33obj,34until,35timeout,36change_event,37}: {38obj: WaitObject;39until: Function;40timeout: number;41change_event: string;42}): Promise<any> {43function wait(cb): void {44let fail_timer: any = undefined;4546function done(err, ret?): void {47obj.removeListener(change_event, f);48obj.removeListener("close", f);49if (fail_timer !== undefined) {50clearTimeout(fail_timer);51fail_timer = undefined;52}53if (cb === undefined) {54return;55}56cb(err, ret);57cb = undefined;58}5960async function f() {61if (obj.get_state() === "closed") {62done(`closed - wait-until - ${change_event}`);63return;64}65let x;66try {67x = await until(obj);68} catch (err) {69done(err);70return;71}72if (x) {73done(undefined, x);74}75}7677obj.on(change_event, f);78obj.on("close", f);7980if (timeout) {81const fail = () => {82done("timeout");83};84fail_timer = setTimeout(fail, 1000 * timeout);85}8687// It might already be true (even before event fires):88f();89}9091return await callback(wait);92}939495