[Compose] Async programming: Thunks

发布时间 2023-10-18 15:01:22作者: Zhentiw

Thunks

Sync thunk: A blocker of code which has everything ready and can return the value directly.

function add(x, y) {
  return x + y
}

const thunk = function() {
  return add(10, 15)
}

thunk() // 25

Ao thunkis pretty much the same as High order function, it can defers the result of another function call, so that you can pass thunk around to deliever the result of that function call. Notice that, the result of the function call can change over time. For example, instead of retrun add(10, 15), return Date.now(). Also thunk is similar to Promise as well.

 

Async thunk: instead of passing params to get value back, now you passing a function, and wait it to be invoke.

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

const thunk = function(cb) {
  return addAsync(10, 15, cb)
}

thunk((sum) => {
    console.log(sum)
}) // 25

The power of async think is we have control over how thing is working inside thunk.

let cache = null
const thunk = function(cb) {
  if (cache) {
    return cache
  }
  cache = addAsync(10, 15, cb)
  return cache
}

For example we can add cache, the first time call the thunk might take a while to do data fetching and calcaultion, but second time it return the results right away.

Which means for consumer, you might find that calling thunk multi times, it might return the data in different time durion. Aysnc thunk normalize the time, for consumer, they don't need to worry about how the callback should be invokded. It becomes time independent.

 

Helper method to make thunk:

function makeThunk(fn) {
  var args = [].slice.call(arguments, 1)
  return function(cb) {
    args.push(cb)
    fn.apply(null, args)
  }
}

Usage:

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

const thunk = makeThunk(addAsync, 10, 15)

thunk((sum) => {
    console.log(sum)
}) // 25