本系列使用 lodash 4.17.4前端
本文件无对引用其余文件的引用web
/** * 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函数实际的应用场景闭包
正如注释中写到的同样app
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异步
好吧我不得不认可我确实想不到其余使用的地方了,请实际在项目中有用过或者有想法的人在评论区告知我,感激涕零。async
其实本函数代码很少,但能够从中窥视一眼闭包的内涵函数
不过因为闭包要讲篇幅实在太长了,我推荐一篇我认为闭包讲得很清楚的博客,原本做者在简书的,不过好像以前由于简书的某些事件而离开简书了,做者最近在找新平台,暂时放一个转载的连接。源码分析
本文章来源于午安煎饼计划Web组 - 梁王this