/*
* The opposite of `before`. This method creates a function that invokes
* `func` once it's called `n` or more times.
* 跟before函数相反,该方法会在调用n次之后触发一次func
*
* @since 0.1.0
* @category Function
* @param {number} n The number of calls before `func` is invoked. func触发之前该方法调用的次数
* @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) { // 闭包,使用的n变量一直是传进after的n
return func.apply(this, args)
}
}
}
lodash方法after详解:达到指定次数后执行
lodash的after函数创建一个在被调用'n'次或更多次后才执行的函数。它用于限制'func'的调用,例如在完成一系列操作后触发某个动作。在提供的示例中,当保存操作完成后两次,'done saving!'会被打印出来。
3405

被折叠的 条评论
为什么被折叠?



