/**
* 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的調用