每日源码分析 - lodash(after.js)

3,045 阅读1分钟

本系列使用 lodash 4.17.4

前言

本文件无对引用其他文件的引用

正文

/**
 * The opposite of `before`. This method creates a function that invokes
 * `func` once it's called `n` or more times.
 *
 * @since 0.1.0
 * @category Function
 * @param {number} n The number of calls before `func` is invoked.
 * @param {Function} func The function to restrict.
 * @returns {Function} Returns the new restricted function.
 * @example
 *
 * const saves = ['profile', 'settings']
 * const done = after(saves.length, () => console.log('done saving!'))
 *
 * forEach(saves, type => asyncSave({ 'type': type, 'complete': done }))
 * // => Logs 'done saving!' after the two async saves have completed.
 */
function after(n, func) {
  if (typeof func != 'function') {
    throw new TypeError('Expected a function')
  }
  return function(...args) {
    if (--n < 1) {
      return func.apply(this, args)
    }
  }
}

export default after

使用方式

// after函数的使用
var finished = () => {
  console.log('Holy sh*t I finished it')
}

var code = after(3, finished)
code() // ...
code() // ...
code() // 'Holy sh*t I finished it'

使用场景

我尽量总结一下after函数实际的应用场景

1. 多个异步请求结束时触发

正如注释中写到的一样

const saves = ['profile', 'settings']
const done = after(saves.length, () => console.log('done saving!'))
forEach(saves, type => asyncSave({ 'type': type, 'complete': done }))
// 当两个异步请求都完成之后会调用() => console.log('done saving!')

尽管我一般会选择Promise.all

2. ...

好吧我不得不承认我确实想不到其他使用的地方了,请实际在项目中有用过或者有想法的人在评论区告知我,感激不尽。

源码分析

其实本函数代码不多,但可以从中窥视一眼闭包的内涵

code函数的闭包

不过由于闭包要讲篇幅实在太长了,我推荐一篇我认为闭包讲得很清楚的博客,本来作者在简书的,不过好像之前因为简书的某些事件而离开简书了,作者最近在找新平台,暂时放一个转载的链接。

前端基础进阶(四):详细图解作用域链与闭包

本文章来源于午安煎饼计划Web组 - 梁王