_.after(n, func)

94

_.after(n, func)

_.after与before方法相对应,创建一个函数,在被调用n次后func才会被调用

参数

n (number): func被调用之前的调用次数
func (Function): 需要被约束的方法

返回值

(Function): 返回新的被约束的方法

例子

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.

源代码:

/**
 * 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.
 */
//与before方法相对应,创建一个函数,在被调用n次后func才会被调用
function after(n, func) {
  if (typeof func != 'function') {//如果func不是function类型,抛出错误
    throw new TypeError('Expected a function')
  }
  return function(...args) {
    if (--n < 1) {//每调用一次这个方法,n就会自减1,当变成0时,返回调用func的结果
      return func.apply(this, args)
    }
  }
}

export default after

 

posted @ 2018-11-12 10:34  hahazexia  阅读(396)  评论(0)    收藏  举报