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

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

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

--

--

--

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.

More from Medium

JavaScript , Git , NoSQL

JavaScript Error Handling