We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Vladislav Stuk • 4 years ago

Jon thank you, great article!

Leo Gonzalez • 4 years ago

Simple and very useful, thanks for sharing!

Ricardo Ruiz • 9 months ago

this is really clear. thanks for the explanation!

Adrian Buciuman • 2 years ago

Correct me if I'm wrong but If I do
const dbOne = new DbClient();
const dbTwo = new DbClient();

I will have 2 different connections because inside the constructor you always set it to null

constructor() {
this.connectionPromise = null;
}

That means that this is not singleton

Tien • 3 years ago

Great article! Thank you. Just wonder whether async is needed in the connect method as there is no await called in the singleton promise case? Cheers

Bruno M • 3 years ago

What if it fails? The database will never be reconnected

Jon Mellman • 3 years ago

Great point, you're right. This is actually discussed in my followup article here: https://www.jonmellman.com/....

Vincenzo Ciancia • 4 years ago

There is still a bug in this code, I believe:

if (!this.connectionPromise) {
this.connectionPromise = connectToDatabase(); // stub
}

if connectToDatabase causes a context switch, then "this.connectionPromise" will still not be assigned, so a second call to getRecord will result in a second call to connectToDatabase()

Jon Mellman • 3 years ago

connectToDatabase is synchronous, so the context switch you're describing isn't possible. Let me know if I'm misunderstanding.

Jérôme Beau • 2 years ago

Maybe you mean it's blocking, but connectToDatabase isn't synchronous, since it's a promise.

Divyanshu • 4 years ago

Absolutely great article. Thanks for sharing Jon