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.
Synchronous Example
[code]
const add = (x,y) => x + y;
const thunk = () => add(1,2);
thunk() // 3
[/code]
Asyncrhonous
[code]
const addAsync = (x,y,callback) => {
setTimeout(function() { callback(x + y) }
}
var thunk = (callback) => addAsync(10,15,callback);
thunk( function() {
sum; // 25
}
[/code]
In the Asynchronous example, the callback inside the thunk shouldn’t have a parameter? like:
thunk( function(sum) {
sum; // 25
}
Thanks for the article.
Zaki, misunderstood on message so disregard my last reply 🙂
You can have parameters in the async callback. It is the way you get information about what you just did outside of the thunk function so unless you are just using the callback as a signal that your async thing is done they are necessary.
The way that I think about thunks is that they are a wrapper around the context needed in order to execute something later, the only difference between the sync and async is the context of async includes a callback function. The callback is your way to communicate outside of the thunk. So the parameters in the callback are necessary when you need the value of some async thing.
Hope that helps,
Thanks for the question!