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
classHelper { privateconstructor() { } privatestaticdb_?: Completer<DB> staticasyncdb(): Promise<DB> { constdb = Helper.db_ if (db) { // connecting, return the promise of the connection returndb.promise } // no connection, create a new connection constcompleter = newCompleter<DB>() Helper.db_ = completer// locked try { constval = awaitconnectDB() completer.resolve(val) // complete success } catch (e) { Helper.db_ = undefined// unlocked to allow subsequent calls to retry the operation
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