lodash-after

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值