What is thunky?
The thunky npm package is designed to delay a function's execution until it's actually needed. It wraps a function in a way that ensures it is only called once, regardless of how many times the wrapper is invoked. This is particularly useful for initialization functions that you don't want to run multiple times or expensive operations that should be deferred until absolutely necessary.
What are thunky's main functionalities?
Lazy initialization
This feature allows for the lazy initialization of resources. The provided code sample demonstrates how a potentially expensive operation (simulated with a setTimeout) is wrapped in a thunky function. Despite calling 'load' twice, the initialization code only runs once, and both calls receive the result once it's available.
const thunky = require('thunky');
let load = thunky((callback) => {
console.log('Initializing...');
setTimeout(() => callback(null, 'Initialization complete'), 1000);
});
load((err, message) => console.log(message));
load((err, message) => console.log(message));
Other packages similar to thunky
once
The 'once' package ensures a function can only be called once. It's similar to thunky in preventing multiple invocations, but it doesn't support lazy initialization. Instead, it's focused on ensuring a function doesn't execute more than once, regardless of its purpose.
memoizee
Memoizee is a comprehensive memoization library that caches the results of function calls based on their arguments. While it serves a different primary purpose than thunky, it achieves a similar effect of avoiding repeated expensive operations. However, memoizee is more versatile in caching multiple calls with different arguments, whereas thunky is focused on single or no-argument functions that need to be delayed or ensured to only run once.
thunky
Delay the evaluation of a paramless async function and cache the result (see thunk).
npm install thunky
Example
Let's make a simple function that returns a random number 1 second after it is called for the first time
var thunky = require('thunky')
var test = thunky(function (callback) {
console.log('waiting 1s and returning random number')
setTimeout(function () {
callback(Math.random())
}, 1000)
})
test(function (num) {
console.log(num)
})
test(function (num) {
console.log(num)
})
Lazy evaluation
Thunky makes it easy to implement a lazy evaluation pattern.
var getDb = thunky(function (callback) {
db.open(myConnectionString, callback)
})
var queryDb = function (query, callback) {
getDb(function (err, db) {
if (err) return callback(err)
db.query(query, callback)
})
}
queryDb('some query', function (err, result) { ... } )
queryDb('some other query', function (err, result) { ... } )
The first time getDb
is called it will try do open a connection to the database.
Any subsequent calls will just wait for the first call to complete and then call your callback.
A nice property of this pattern is that it easily allows us to pass any error caused by getDb
to the queryDb
callback.
Error → No caching
If the thunk callback is called with an Error
object as the first argument it will not cache the result
var fails = thunky(function (callback) {
console.log('returning an error')
callback(new Error('bad stuff'))
})
fails(function (err) {
console.log(err)
});
fails(function (err) {
console.log(err)
})
Promise version
A promise version is available as well
var thunkyp = require('thunky/promise')
var ready = thunkyp(async function () {
return 42
})
await ready()
License
MIT