Demystifying JavaScript Thunks: Managing Asynchronous Operations with Examples

Explore how thunks enhance JavaScript code by simplifying asynchronous tasks

Photo by Rahul Mishra on Unsplash

The concept of thunks has been around in programming for a long time, and it’s not specific to JavaScript. However, thunks gained significant attention in the JavaScript community in the context of handling asynchronous operations and state management, particularly with libraries like Redux.

Thunks became popular in the JavaScript ecosystem around 2015 when the Redux library started advocating their use. Redux uses thunks as a middleware to handle asynchronous actions and side effects.

Today we will be exploring thunks in detail in general, not specific to redux.

What are thunks?

In terms of Synchronous perspective, a thunk is a function that has everything already that it needs to do, to give some value back, we don’t have to pass anything to get the value.

In another words, A thunk is just a function with some closure state, keeping track of value(s), and it gives you the values back when you can it.

Lets understand this by an example:

Characteristics of a thunk function:

They do not require any parameters.

It is a. function wrapper around some state or token value.

Thunk function can be called infinite times, on each call output will be same.

Thunk function can be treated as value, and can be passed over anywhere in the program. Wherever we want the value, we can simply call the thunk without worrying about the parameters.

Philosophical Definition

Philosophical explanation: The term “thunk” is believed to have been coined as a humorous blend of the words “think” and “chunk,” indicating that a thunk is a “chunk of code to think with.” In essence, a thunk is a function that encapsulates an expression to be evaluated later. It’s used to defer the evaluation of an expression until it’s actually needed, often to improve performance or manage control flow in a more efficient way.

There are two flavours for Thunk:

1. synchronous thunk

function sum(n1,n2) {
return n1+ n2;
}

var thunk = function() {
return sum(80, 90)
}

console.log(thunk()); // 170

2. asynchronous thunk

A function, which has everything to do its job, except a callback.
This callback is called, when the async job is done.

Async thunk uses closure to maintain the state.

What problem does async thunk solves?

It gives us the ability to execute async tasks sequentially without invoking any other APIs (Like Promise API or any other third party tools)

It solves the problem of time. We don’t have to worry when the value in callback is available.

By wrapping asyncSum in function, we have removed the time.

We don’t have to worry about completion of asynSum , whenever it gets completed, our callback passed in thunk get’s executed.

Here are 2 examples to demostrate the usage of async thunks:

// Example 1: Asynchronous Thunk using Callbacks
function asyncThunk(callback) {
setTimeout(() => {
const data = "Async data";
callback(data);
}, 1000);
}

function handleAsyncData(data) {
console.log("Received data:", data);
}

asyncThunk(handleAsyncData);

// Example 2: Asynchronous Thunk using Event Listener

function asyncThunk(eventListener) {
setTimeout(() => {
const eventData = { message: "Async event data" };
eventListener(eventData);
}, 1500);
}

function handleEvent(eventData) {
console.log("Event data received:", eventData.message);
}

asyncThunk(handleEvent);

Here is a utility function that creates async thunk

function cookThunk(fn) {
var args = [].slice.call(arguments, 1);
// converts the arguments object into a proper array by using the slice method
// slice will extract elements starting from index 1,
// because in 0 index we have function as an argument.

return function(cb) {
args.push(cb);
fn.apply(null,args);
}
}

Consuming it:

function asyncSum(n1,n2,cb) {
setTimeout(function() {
cb(n1 + n2);
}, 1000);
}

var thunk = cookThunk(asyncSum, 1, 2);

thunk(function(res){
console.log(res); // 3
});

“Embrace the power of thunks to elegantly manage asynchronous tasks and delayed executions in your JavaScript code. With thunks, you can simplify complexity, improve control flow, and create more efficient and organized solutions for your programming needs.”

Thanks for reading.

--

--

राहुल मिश्रा
राहुल मिश्रा

Responses (1)