理解辩解。 thunk和赋值返回

时间:2016-09-10 01:27:20

标签: javascript asynchronous underscore.js lodash redux-thunk

我仍在努力理解为什么thunks有用。我听到的是以下内容:

  1. 在thunk周围创建闭包,这意味着保留了上下文
  2. 问题:如果代码块已经保存在函数表达式中,为什么上下文很重要?

    示例:

    function debounce(func, delay) {
      var inDebounce = undefined;
    
      console.log("GOOD DEBOUNCE")
    
      return function(){
        var context = this, args = arguments
    
        // why can't context be null? or under debounce?
    
        clearTimeout(inDebounce);
        return inDebounce = setTimeout(function() {
          return func.apply(context, args)
        }, delay)
      }
    }
    
    1. Thunks允许重复调用函数
    2. 我看到一个例子介绍了像

      之间的区别

      设x = 1 + 2 并且让x =()=>返回1 + 2

      允许我们多次返回3次

      function debounce2(func, delay) {
        var inDebounce = undefined;
        console.log("BAD DEBOUNCE")
        var context = this, args = arguments
        clearTimeout(inDebounce);
          return inDebounce = setTimeout(function() {
            return func.apply(context, args)
          }, delay) 
      

      这个例子不起作用。它在document.load上被调用一次,我无法使用该应用程序进行任何API调用。

      编辑// IGNORE低于此系列。我阅读了文档

      所以在这种情况下,它是有道理的,但这有什么意义呢?

      return inDebounce = setTimeout(function() {
        return func.apply(context, args)
      }, delay) 
      

      这条线似乎正在返回作业?

1 个答案:

答案 0 :(得分:1)

返回inDebounce。最后一段代码相当于:

inDebounce = setTimeout(function() {
  return func.apply(context, args)
}, delay);
return inDebounce;