jpcasa
12/20/2018 - 7:08 PM

JS Thunks

A thunks is a function that contains all of the context (state, functions, etc) it will need in order to carry out some sort of logic in the future.

Another way to say that, they are a function closure that begins with all of the arguments it will need in order to execute. You just don’t want to execute it now, it will be sometime in the future.

  1. thunk is a function that encapsulates synchronous or asynchronous code inside.
  2. thunk accepts only one callback function as an arguments, which is a CPS function.
  3. thunk returns another thunk function after being called, for chaining operations.
  4. thunk passes the results into a callback function after being excuted.
  5. If the return value of callback is a thunk function, then it will be executed first and its result will be sent to another thunk for excution, or it will be sent to another new thunk function as the value of the computation.
const add = (x,y) => x + y;
 
const thunk = () => add(1,2);
 
thunk() // 3
const addAsync = (x,y,callback) => {
  setTimeout(function() { callback(x + y) }
}
 
var thunk = (callback) => addAsync(10,15,callback);
 
thunk( function() {
  sum; // 25
}