本系列使用 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 函数实际的应用场景
正如注释中写到的一样
- 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
好吧我不得不承认我确实想不到其他使用的地方了,请实际在项目中有用过或者有想法的人在评论区告知我,感激不尽。
其实本函数代码不多,但可以从中窥视一眼闭包的内涵
不过由于闭包要讲篇幅实在太长了,我推荐一篇我认为闭包讲得很清楚的博客, 本来作者在简书的,不过好像之前因为简书的某些事件而离开简书了,作者最近在找新平台,暂时放一个转载的链接。
本文章来源于午安煎饼计划 web 组 - 梁王
来源: https://juejin.im/post/5a337ccd6fb9a045055e2f68