Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/easyts/async.ts>Completer

js library written with ts, use select and chan like golang in js.
Latest
class Completer
import { Completer } from "https://deno.land/x/easyts@0.1.3/async.ts";

Create a Promise with a completion marker

Examples

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
    }
}

Constructors

new
Completer()

Properties

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

Returns whether the Promise has completed

readonly
promise: Promise<T>

Returns the created Promise

Methods

reject(reason?: any): void

Complete error, Promise.reject(reason)

resolve(value?: T | PromiseLike<T>): void

Complete success, Promise.resolve(value)