Singleton with async constructor in JavaScript

There are different flavors of Singleton.
let instance;
const getInstance = () => {
if (!instance) {
instance = new Date();
}
return instance;
}

Async/Await

For asynchronous instance creation we can use following code:

const net = async () => await new Promise(resolve => setTimeout(resolve, 1000));let instance;
const getInstance = async () => {
if (!instance) {
instance = await net();
}
return instance;
}

JavaScript is single-threaded, but beware of context switches

The most reasonable solution is with simple async/await. It does not guarantee that constructor will be invoked only once, but at least once. Other requests will likely await Promise resolution — that’s the price to pay.

let instance;
let semaphore = false;
const getInstance = async () => {
if (!instance && !semaphore) {
semaphore = true; // mark awaited constructor
instance = await net();
}
return instance;
}

Bonus: blocking constructor in Node.js runtime

Bonus: in Node.js the heavy and blocking constructor can be invoked during server startup time. For that the code does not even have to be async, we can easily block the main thread loop. This way it can be initialized once and then instance can be exported via CommonJS module variable. That’s the simplest solution, but available only in Node.js runtime.

--

--

Father. Husband. Solutions developer profesionally (software quite often). Arsenal supporter. Cyclist.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Brodziak

Adam Brodziak

Father. Husband. Solutions developer profesionally (software quite often). Arsenal supporter. Cyclist.