What are thunk functions ?

Kyle Simpson talked about thunk functions in his "rethinking asynchronous programming" course, his lecture made me learn thunk functions in depth. In this post I explain everything I learned about thunk functions.

Thunk functions basics

Thunk function do not take arguments and evaluate their statement when they are called. Below is an example of thunk functions.

function addTwoValues(value1, value2) {
    return value1 + value2;
}

let thunk = function() {
    return addTwoValues(10, 20)
}

thunk();

Thunk function are used to delay evaluation of expression. Instead of evaluating 10+20 directly we wrapped it in a function to execute it when needed.

Asynchronous thunk functions

Asynchronous thunk are similar to synchronous thunks except that they also accept a callback to run after they finished evaluating their internal expressions.

function addAsync(x, y, callback) {
  setTimeout(() => {
    callback(x + y)
  }, 1000)
}


var thunk = function (callback) {
  addAsync(10, 15, callback)
}


thunk(function (sub) {
  console.log(sub);
})

In the snippet above we add run our callback asynchronously. We used setTimeout, but it could have been any asynchronous function.

Where does thunk functions come from ?

Thunk functions are pretty old. In early days, as the compilers have been experimenting evaluation strategies, one of the experiments has been Thunks to delay execution of expressions.

Further reading:

Kyle simpson explains Thunk functions in his course Rethinking Asynchronous JavaScript (This post is also highly inspired by his talk). The Wikipedia article on Thunks is also a worthfull resources.