每日原始碼分析 – lodash(after.js)

樑王發表於2019-03-02

本系列使用 lodash 4.17.4

前言

本檔案無對引用其他檔案的引用

正文

/**
 * 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`)
  }
  return function(...args) {
    if (--n < 1) {
      return func.apply(this, args)
    }
  }
}

export default after
複製程式碼

使用方式

// after函式的使用
var finished = () => {
  console.log(`Holy sh*t I finished it`)
}

var code = after(3, finished)
code() // ...
code() // ...
code() // `Holy sh*t I finished it`
複製程式碼

使用場景

我儘量總結一下after函式實際的應用場景

1. 多個非同步請求結束時觸發

正如註釋中寫到的一樣

const saves = [`profile`, `settings`]
const done = after(saves.length, () => console.log(`done saving!`))
forEach(saves, type => asyncSave({ `type`: type, `complete`: done }))
// 當兩個非同步請求都完成之後會呼叫() => console.log(`done saving!`)
複製程式碼

儘管我一般會選擇Promise.all

2. …

好吧我不得不承認我確實想不到其他使用的地方了,請實際在專案中有用過或者有想法的人在評論區告知我,感激不盡。

原始碼分析

其實本函式程式碼不多,但可以從中窺視一眼閉包的內涵

每日原始碼分析 – lodash(after.js)
code函式的閉包

不過由於閉包要講篇幅實在太長了,我推薦一篇我認為閉包講得很清楚的部落格,本來作者在簡書的,不過好像之前因為簡書的某些事件而離開簡書了,作者最近在找新平臺,暫時放一個轉載的連結。

前端基礎進階(四):詳細圖解作用域鏈與閉包

本文章來源於午安煎餅計劃Web組 – 樑王

相關文章