LoginSignup
22
13

More than 5 years have passed since last update.

【JavaScript】うるせぇお前がGolangになるんだよ

Last updated at Posted at 2018-07-25

最近、Golangのif err != nilがどうのこうのと盛り上がっていますが、いかがお過ごしでしょうか?エラーを多値で返すのは面白いですね。

jsでもこれを実現するライブラリを書いてみました。

akameco/golangify: Golang like error handling for async/await

$ yarn add golangify
const go = require('golangify')

const success = x => Promise.resolve(x + x)
const failure = () => Promise.reject(new Error('err'))

const main = async () => {
  console.log(await go(success)(1))
  // => [ 2, null ]

  const [result, err] = await go(failure)()
  if (err !== null) {
    console.log(err.message)
    // => err
  }
  console.log(result)
  // => null
}

main()

はい、golangifyでラップされたasyncな関数はその関数の結果とエラーを多値で返します。

const [result, err] = await go(failure)()

エラーがない場合は[result, null]、エラーがある場合は、[null, error]を返します。

面倒なのでsync関数は対応してないですが、実装自体はシンプルです。

const golangify = target => new Proxy(target, {
  apply(target, prop, args) {
    const result = Reflect.apply(target, prop, args)
    return result.then
      ? result.then(v => [v, null]).catch(err => [null, err])
      : result
  },
})

Reflect.applyで実行して、Promiseならばそれを解決してthen/catchでそれぞれ配列を返すようにしてるだけです。
Proxyを使うとメタ的な処理を追加できるので楽しいですね。

おわり

気が向いたらスターしてください。

akameco/golangify: Golang like error handling for async/await

関連

【Proxy】JavaScriptでRubyのtimesを使う - Qiita

22
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
13