Skip to content

Thunk and Closure

daisho edited this page Sep 28, 2021 · 1 revision

Today, I learned an interesting concept: Thunk

Thunk behaves like a Promises but they are not the same thing according to someone who taught me this.

function getFile(file) {
  let text, fn

  fakeAjax(file, response => {
    if (fn) {
      fn(response)
    } else {
      text = response
    }
  })

  return cb => {
    if (text) {
      cb(text)
    } else {
      fn = cb
    }
  }
}

function fakeAjax(url, cb) {
  const fake_responses = {
    file1: 'The first text',
    file2: 'The middle text',
    file3: 'The last text',
  }
  const randomDelay = (Math.round(Math.random() * 1e4) % 8000) + 1000

  console.log('Requesting:', url)

  setTimeout(function () {
    cb(fake_responses[url])
  }, randomDelay)
}

const thunk = getFile('file')

thunk(res => {
  console.log('Response:', res)
})

This is so interesting.

Clone this wiki locally