Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

1.2 KB
Raw Blame
/* Copyright 2026 Marimo. All rights reserved. */

/**
 * A deferred promise that can be resolved or rejected externally.
 *
 * Provides synchronous access to status and resolved value, useful for
 * cases where you need to check if a promise has settled without awaiting it.
 */
export class Deferred<T> {
  public promise: Promise<T>;
  public resolve!: (value: T | PromiseLike<T>) => void;
  public reject!: (reason?: unknown) => void;
  public status: "pending" | "resolved" | "rejected" = "pending";
  public value: T | undefined = undefined;

  public constructor() {
    this.promise = new Promise<T>((resolve, reject) => {
      this.reject = (reason: unknown) => {
        this.status = "rejected";
        reject(reason as Error);
      };
      this.resolve = (value) => {
        this.status = "resolved";
        // Store the value for synchronous access
        if (!isPromiseLike(value)) {
          this.value = value;
        }
        resolve(value);
      };
    });
  }
}

function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
  return (
    typeof value === "object" &&
    value !== null &&
    "then" in value &&
    typeof value.then === "function"
  );
}