Promise 作ってました
- カテゴリ:
- JavaScript
- コメント数:
- Comments: 0
◆ シンプルなようでちょっと複雑
Promise を使った関数を使うことや Promise を使う関数を作ることがあって Promise があまり理解してないなぁ と思ったので中身を知るために作ってみました
仕様とか ES のポリフィル探せばどうなってるか書いてそうですが 読んでるより書いてるほうが好きだしちゃんと理解ができると思うので 1 から作ってます
情報は Chrome で Promise 関数を動かした時にどんな値が返ってくるかを見るだけ
ググることはしてないです
結果はこんな感じ
実行してみると
all とか race は実装してないですが 基本的な then と catch のチェーンはちゃんと動いてるはずです
直列のチェーンでも並列のチェーンでもできてます
これで Promise 対応してないブラウザでも困りませんね
そんな機会なさそうですが
1 時間もあればできそうと思っていたのに 4 時間近く?も掛かってしまいました
まだまだです
仕様とか ES のポリフィル探せばどうなってるか書いてそうですが 読んでるより書いてるほうが好きだしちゃんと理解ができると思うので 1 から作ってます
情報は Chrome で Promise 関数を動かした時にどんな値が返ってくるかを見るだけ
ググることはしてないです
結果はこんな感じ
実行してみると
var p = promise((a,b) => setTimeout(a, 1000, 12))
p.then(e => console.log(e))
p.then(e => console.log(e+1))
p.then(e => console.log(e+2))
// 12
// 13
// 14
var p = promise((a,b) => setTimeout(a, 1000, 16))
p.then(e => e / 4).then(e => e + 2).then(e => console.log(e * e))
// 36
var p = promise((a,b) => setTimeout(b, 1000, 16))
p.then(e => console.log(e)).catch(e => console.log(-e))
// -16
promise((a,b) => setTimeout(a, 1000, 1))
.then(e => promise((a,b) => setTimeout(a, 1000, e+1)))
.then(e => console.log(e))
// 2
promise((a,b) => a())
.then(e => promise.reject())
.catch(e => console.log(111))
// 111
promise((a,b) => a(1)).then(e => no_defined_value).catch(e => console.log(e))
// ReferenceError: no_defined_value is not defined(…)
promise((a,b) => no_defined_value).then(e => 1).catch(e => console.log(e))
// ReferenceError: no_defined_value is not defined(…)
p.then(e => console.log(e))
p.then(e => console.log(e+1))
p.then(e => console.log(e+2))
// 12
// 13
// 14
var p = promise((a,b) => setTimeout(a, 1000, 16))
p.then(e => e / 4).then(e => e + 2).then(e => console.log(e * e))
// 36
var p = promise((a,b) => setTimeout(b, 1000, 16))
p.then(e => console.log(e)).catch(e => console.log(-e))
// -16
promise((a,b) => setTimeout(a, 1000, 1))
.then(e => promise((a,b) => setTimeout(a, 1000, e+1)))
.then(e => console.log(e))
// 2
promise((a,b) => a())
.then(e => promise.reject())
.catch(e => console.log(111))
// 111
promise((a,b) => a(1)).then(e => no_defined_value).catch(e => console.log(e))
// ReferenceError: no_defined_value is not defined(…)
promise((a,b) => no_defined_value).then(e => 1).catch(e => console.log(e))
// ReferenceError: no_defined_value is not defined(…)
all とか race は実装してないですが 基本的な then と catch のチェーンはちゃんと動いてるはずです
直列のチェーンでも並列のチェーンでもできてます
Promise
├then→then
├then→catch
└catch
then で Promise オブジェクトを返したときのバッチリです├then→then
├then→catch
└catch
これで Promise 対応してないブラウザでも困りませんね
そんな機会なさそうですが
1 時間もあればできそうと思っていたのに 4 時間近く?も掛かってしまいました
まだまだです