What is a Thunk?

栏目: IT技术 · 发布时间: 4年前

内容简介:“Thunk” is one of those programming terms that sounds intimidating, but many of us are actually familiar with and have used them. Let’s first see how Wikipedia defines thunks[1]:This offers a little help, but maybe is a little too abstract.So, what is a th

“Thunk” is one of those programming terms that sounds intimidating, but many of us are actually familiar with and have used them. Let’s first see how Wikipedia defines thunks[1]:

In computer programming, a thunk is a subroutine used to inject an additional calculation into another subroutine. Thunks are primarily used to delay a calculation until its result is needed, or to insert operations at the beginning or end of the other subroutine.

This offers a little help, but maybe is a little too abstract.

So, what is a thunk really? It’s simply a function returned from another function . Let’s look at a quick example in JavaScript:

function delayedLogger(message, delay) {
  return function(logger) {
    setTimeout(function() {
      logger(message);
    }, delay);
    logger(message);
  };
}

In this example, when we call the delayedLogger function, it returns a thunk . We can then pass that thunk a logger parameter, which will be executed after the specified delay .

const thunk = delayedLogger('See you in a bit', 2000);
thunk(console.log);

In this example, we’ll see "See you in a bit" logged to the console after two seconds.

Bonus: Use in Redux

If you’re familiar with Redux, you likely know the concept of action creators : functions that return action objects. The following is an example of an action creator that makes an action that adds a product to a shopping cart:

function addToCart(product) {
  return {
    type: 'ADD_TO_CART',
    payload: product,
  };
}

It turns out that we need a little more flexibility with our action creators: we need to be able to dispatch an action asynchronously: often after we perform a fetch request to save or load data from an API. We can solve this issue by using redux-thunk , a Redux middleware that allows us to return thunks from action creators [2].

Let’s mock up what this would look like. We’ll load a list of products from an API and then dispatch an action with those loaded products.

function loadProducts() {
  // Return a thunk
  return function(dispatch) {
    fetch('some-product-api-url')
      .then(res => res.json())
      .then(data => {
        dispatch({
          type: 'ADD_PRODUCTS',
          payload: data.products,
        });
      });
  };
}

And there we have it: A more practical application of the thunk concept!

References:

  1. Wikipedia: Thunk
  2. redux-thunk

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Effective Java 中文版

Effective Java 中文版

(美)Joshua Bloch / 潘爱民 / 机械工业出版社 / 2003-1 / 39.00元

本书介绍了在Java编程中57条极具实用价值的经验规则,这些经验规则涵盖了大多数开发人员每天所面临的问题的解决方案。通过对Java平台设计专家所使用的技术的全面描述,揭示了应该做什么,不应该做什么才能产生清晰、健壮的高效的代码。 本书中的每条规则都以简短、独立的小文章形式出现,这些小文章包含了详细而精确的建议,以及对语言中许多细微之处的深入分析,并通过例子代码加以进一步说明。贯穿全书的是通用......一起来看看 《Effective Java 中文版》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码