5
2

More than 1 year has passed since last update.

Elixirから覚えるJavaScript 〜Promise(文法遊び)〜 

Posted at

僕は普段は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

無事に同じ結果になりました

5
2
1

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
5
2