thunk 是一个不带参数并返回某些内容(或作为副作用执行某些操作)的函数。惰性求值是将表达式的求值推迟到以后的过程,这可以通过 thunk 来完成:
// Not lazy
var value = 1 + 1 // immediately evaluates to 2
// Lazy
var lazyValue = () => 1 + 1 // Evaluates to 2 when lazyValue is *invoked*
你也可以让返回值变得懒惰:
// Not lazy
var add = (x, y) => x + y
var result = add(1, 2) // Immediately evaluates to 3
// Lazy
var addLazy = (x, y) => () => x + y;
var result = addLazy(1, 2) // Returns a thunk which *when evaluated* results in 3.
最后我们可以推迟一些异步操作:
// Not lazy
var callApi = spec => fetch(spec.url, spec.options);
// Immediately returns a Promise which will be fulfilled when the network response is processed.
var result = callApi({url: '/api', options: {}});
// Lazy
var callApiLazy = spec => () => fetch(spec.url, spec.options);
var result = callApiLazy({url: '/api', options: {}});
// result is a thunk that when evaluated will return a Promise ...
// which will be fulfilled when the network response is processed.
现在 thunk 没有有接受零参数 - 您可以返回一个需要更多参数才能成功评估的惰性值。这被称为“currying”:
// Curried add (not lazy)
var add = x => y => x + y
var add3 = add(3)
var result = add3(7) // Immediately evaluates to 10
redux-thunk 允许您将函数而不是对象作为操作返回,并使用 dispatch 函数调用您的函数。然后,您可以同步或异步地懒惰地产生一个(或多个)动作。大多数时候,您会希望使用它来允许您异步调度。
另见: