Class Completer<T>

Create a Promise with a completion marker

Remarks

Completer is inspired by dart, it can be used to return the same piece of data for the same asynchronous request. For example, you have a database singleton that only returns the same connection when the database is actually requested.

Example

Suppose we have a connect function that creates a connection to the database and its signature looks like this function connectDB():Promise<DB>. We can use the Completer wrapper to create only one connection

class Helper {
private constructor() { }
private static db_?: Completer<DB>
static async db(): Promise<DB> {
const db = Helper.db_
if (db) {
// connecting, return the promise of the connection
return db.promise
}
// no connection, create a new connection
const completer = new Completer<DB>()
Helper.db_ = completer // locked
try {
const val = await connectDB()
completer.resolve(val) // complete success
} catch (e) {
Helper.db_ = undefined // unlocked to allow subsequent calls to retry the operation

completer.reject(e) // complete error
}
return completer.promise
}
}

Type Parameters

  • T

Hierarchy

  • Completer

Constructors

Properties

Accessors

Methods

Constructors

Properties

c_: boolean = false
promise_: undefined | Promise<T>
reject_: undefined | ((reason?: any) => void)
resolve_: undefined | ((value?: T | PromiseLike<T>) => void)

Accessors

  • get isCompleted(): boolean
  • Returns whether the Promise has completed

    Returns boolean

  • get promise(): Promise<T>
  • Returns the created Promise

    Returns Promise<T>

Methods

  • Complete error, Promise.reject(reason)

    Parameters

    • Optional reason: any

    Returns void

  • Complete success, Promise.resolve(value)

    Parameters

    • Optional value: T | PromiseLike<T>

    Returns void

Generated using TypeDoc