delay the evaluation of a paramless async function and cache the result
Delay the evaluation of a paramless async function and cache the result (see thunk).
npm install thunky
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 // the inner function should only accept a callbackconsole.log'waiting 1s and returning random number';setTimeoutcallbackMathrandom;1000;;test // inner function is called the first time we call testconsole.lognum; // prints random number;test // subsequent calls waits for the first call to finish and return the same valueconsole.lognum; // prints the same random number as above;
Thunky makes it easy to implement a lazy evaluation pattern.
var getDb = thunkydbopenmyConnectionString callback;;vargetDbif err return callbackerr;dbqueryquery callback;;;queryDb'some query' ;queryDb'some other query' ;
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
If the thunk callback is called with an
Error object as the first argument it will not cache the result
var fails = thunkyconsole.log'returning an error';callback'bad stuff';;fails // inner function is calledconsole.logerr;;fails // inner function is called again as it returned an error beforeconsole.logerr;;