after.js
/**
* 该函数用于创建一个新的函数,只有在被调用了指定的次数(n 次或更多次)后,才会执行给定的输入函数(func)。
*
* @since 0.1.0
* @category Function
* @param {number} n 一个数字,表示在执行 func 之前新返回的函数应该被调用的最小次数。
* @param {Function} func 在达到 n 次调用后应该执行的函数。
* @returns {Function} 该函数用于创建一个新的函数,只有在被调用了指定的次数(n 次或更多次)后,才会执行给定的输入函数(func)。
* @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) {
// 如果 func 不是一个函数,则函数会抛出一个带有消息 "Expected a function" 的 TypeError。
if (typeof func !== 'function') {
throw new TypeError('Expected a function')
}
// 如果未提供 n,它会为其设置默认值为 0。
n = n || 0
// 返回一个新的函数,这个新函数接受任意数量的参数(使用 ...args 收集参数)
return function(...args) {
if (--n < 1) {
return func.apply(this, args)
}
}
}
export default after
在示例中,after 函数用于创建一个名为 done 的新函数,该函数在被调用了指定次数(saves.length 次)后,会执行 console.log('done saving!')。这个示例还使用了 forEach 来遍历 saves 数组,每次调用 asyncSave 函数,并将 done 作为回调函数传递给 asyncSave,以便在异步保存完成后触发 "done saving!" 日志。这种方式可以确保在所有异步保存操作完成后,才会执行 console.log。