/**
* 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')
}
n = n || 0
return function(...args) {
if (--n < 1) {
return func.apply(this, args)
}
}
}
export default after
示例
var saves = ['profile', 'settings'];
var done = _.after(saves.length, function() {
console.log('done saving!');
});
_.forEach(saves, function(type) {
asyncSave({ 'type': type, 'complete': done });
});
// => Logs 'done saving!' after the two async saves have completed.
两个入参,第一个为number,第二个为function,返回一个函数
_.before的反向函数;此方法创建一个函数,当他被调用n或更多次之后将马上触发func 。
可以拓展的地方,在于,可以设置条件,然后才能使用此函数,这里的条件是n次数,做业务的时候,可以设置某某为true的时候才能调用,就是因为有apply这里托底;
这函数跟防抖和节流还有类似的地方,成功创建之后,无论调用(n)多少次,最终只执行最后一次,但不同的是,它不一定执行,它要求一定要执行多少次才能执行,不像节流防抖一样,一定会执行一次;
使用场景:
示例看起来就好像一个有意义的场景,调用保存接口,调用了两次,两次之后再执行complete这个回调,那么asyncSave这个封装的方法得注意,complete必须每次成功都得调用,那么才能再最后一次实现done的调用