小白关于loadsh _.after的问题

官方api的例子写的太简洁
var saves = ['profile', 'settings'];

var done = _.after(saves.length, function() {
console.log('done saving!');
});

_.forEach(saves, function(type) {
asyncSave({ 'type': type, 'complete': done });
});
不是很懂....求大神解释下### 题目描述

阅读 1.7k
2 个回答

首先看API,大概理解是返回一个函数,等待执行n次后,执行func

n: The number of calls before func is invoked.
Returns
(Function): Returns the new restricted function.

再看源码,就理解了,其实就是一个闭包,控制n

function after(n, func) {
      if (typeof func != 'function') {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      n = toInteger(n);
      return function() {
        if (--n < 1) {
          return func.apply(this, arguments);
        }
      };
    }
var done = _.after(n, func)
this method creates a function that invokes func once it's called n or more times.

意思是说 done 这个函数被调用n次或n次以上时,执行 func 函数。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题