無痛支援 ES6 Promise

讓現有的 Callback 介面無痛升級!

昨天我們 Carl Su 說要導入 Slack 所以就在 npm 上找了一下 Node.js 上的 slack module,沒想到找到的是吸捨大大寫的,看了 Source code 發現沒有支援 Promise,所以思考了一下比較無痛的解決方式。

在 Facebook 上,Tom Chen 提到可以使用 native-or-bluebird,這個 module 我在 pretty-redis(沒在維護了,改成另一專案 redis-mount) 使用過,個人覺得使用時候最好同時把 bluebird 裝起來,因為使用者可能看到 Error Message 就荒了,另一個問題是我們的 js 要不要同時支援 Browser?需要支援的話就不太適合使用 native-or-bluebird,bluebird 程式太大。

使用現有 Callback 介面,同時讓他支援 Promise


  1. 判斷 callback 存不存在,沒有使用 native-or-bluebird 的情況需要再判斷 Promise 存不存在。
  2. 存在的情況下直接執行 function 並把 callback 傳入
  3. 不存在的情況下建立 promise,並把 resolve, reject 轉換成一般 callback function。

不使用 native-or-bluebird:

https://gist.github.com/poying/830d4efb4c65ac4aaba0

使用 native-or-bluebird:

https://gist.github.com/poying/26dfa50175f703fe26d5

修改現有 API

https://gist.github.com/poying/17834057283903662621

或是再更無痛一點:

https://gist.github.com/poying/e3f442b29672526d7709
https://gist.github.com/poying/a832a62334c38d5ac9ef