僕は普段はElixirを使ってます
必要になったのでJavaScriptの勉強をはじめました
題名はElixirから覚えるJavaScriptですが、逆もできるかも?
今日はPromiseを見てみたいと思います
本来は非同期で使いますが、なんとなくElixirのパイプ風にしてみたかった
意味はあまりなく文法遊びです
お題
10を初期値
|> 結果表示
|> 10倍
|> 結果表示
|> 12足す
|> 結果表示
Elixir
10
|> IO.inspect()
|> then(& &1 * 10)
|> IO.inspect()
|> then(& &1 + 12)
|> IO.inspect()
実行結果
10
100
112
JavaScript
const promise = new Promise((resolve, reject) => {
resolve(10);
});
const inspect = (x) => {
console.log(x);
return x;
}
promise.then((x) => inspect(x))
.then((x) => x * 10)
.then((x) => inspect(x))
.then((x) => x + 12)
.then((x) => inspect(x));
実行結果
10
100
112
無事に同じ結果になりました