Strona domowa

Witam na mojej prywatnej stronie internetowej!

[If this is all Polish to you, click here: English]

Uwaga: z oczywistych powodów nie mogę zagwarantować swojej nieomylności, choć staram się o zgodność tego, co piszę, z Prawdą. Jest również oczywiste, że nie gwarantuję takiej zgodności w przypadku komentarzy. Umieszczenie linku do strony spoza niniejszego serwisu nie musi oznaczać, że podzielam poglądy autora tej strony, a jedynie, że uważam ją za wartościową z takich czy innych powodów.

Marcin ‘mbork’ Borkowski

2020-08-03 Look up a global variable in the database in Node.js

Today I encountered an interesting problem. Assume that you want a global constant in your Node.js backend, but its actual value is to be taken from a database. This means that fetching the constant should be done asynchronously. Unless you use Node.js 14.3.0 or newer (which as the time of me writing this is not yet ubiquitous), you cannot await your database request at the top level like this:

const CONST = await Database.fetch();
// the rest of the code using CONST

(of course, Database.fetch is a fictional function returning a promise).

Still, it is fairly easy to make it work anyway with Immediately Invoked Async Function Expressions. For instance, you can say this:

const CONST = Database.fetch();
(async function() {
	const DOUBLE_CONST = 2 * await CONST;
	const TRIPLE_CONST = 3 * await CONST;
})();

The takeaway here is that the potentially time-consuming Database.fetch() will only be run once, and the value recorded and used in subsequent uses of await CONST without waiting more. Here is a short proof of the above claims:

const long_random_promise = new Promise(resolve => {
	setTimeout(() => {
		resolve(Math.random());
	}, 2000);
});

(async function() {
	console.log(await long_random_promise);
	console.log(await long_random_promise);
})();

Two seconds after launching this script in Node.js (or browser, for that matter), the same value will be logged twice in quick succession.

Granted, this technique is not the most beautiful one, but should suffice until everyone is going to have newer Node.js versions.

CategoryEnglish, CategoryBlog

Comments on this page

More...