import { Completer } from "https://deno.land/x/easyts@0.1.3/mod.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
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
}
}