Austin Story

Ruby, Rails and Javascript Blog

Powered by Genesis

What is a thunk in javascript?

October 25, 2016 By Austin Story 2 Comments

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]

Filed Under: Javascript, Theory Tagged With: Javascript, thunk

Categories

  • AngularJS
  • Books
  • Devise
  • Elasticsearch
  • ES6
  • Information Security
  • Integrations
  • Javascript
  • Linux
  • Minitest
  • PhoneGap
  • Programming
  • React
  • Redux
  • Ruby
  • Ruby on Rails
  • Stripe
  • Testing
  • Theory
  • TypeScript
  • Uncategorized
  • Vue
  • Webpack