Created
May 23, 2019 05:08
-
-
Save yuroyoro/1f5a65dcfcb004c4c7be9af5ce775419 to your computer and use it in GitHub Desktop.
async/awaitとpromise使えばモナド糖衣構文っぽいの書けそうだよねって思って書いてみたけど、async () => {} でwrapしないといけないしまぁそんなにきれいに書けなかったって話。でもこういう邪悪なことやる関数型厨いそうですよね?(オマエだよ)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Optional container like maybe monad | |
class Option { | |
constructor(value){ | |
this.value = value | |
} | |
async promise() { | |
return new Promise((resolve, reject) => { | |
if (this.value) { | |
resolve(this.value); | |
} else { | |
reject(undefined); | |
} | |
}); | |
} | |
} | |
const o1 = new Option("foo"); | |
const o2 = new Option("bar"); | |
const o3 = new Option(null); | |
(async () => { | |
try { | |
const v1 = await o1.promise(); | |
const v2 = await o2.promise(); | |
console.log(v1, v2); | |
} catch {} | |
})(); // => foo bar | |
(async () => { | |
try { | |
const v1 = await o1.promise(); | |
const v2 = await o2.promise(); | |
const v3 = await o3.promise(); | |
console.log(v1, v2, v3); | |
} catch {} | |
})(); // do nothing | |
// introduce doM emulates do-like syntax sugar | |
async function doM(f1, f2) { | |
try { | |
return f1(); | |
} catch { | |
if (f2) { | |
return f2(); | |
} | |
} | |
} // => foo bar | |
doM(async () => { | |
const v1 = await o1.promise(); | |
const v2 = await o2.promise(); | |
console.log(v1, v2); | |
}); | |
doM(async () => { | |
const v1 = await o1.promise(); | |
const v2 = await o2.promise(); | |
const v3 = await o3.promise(); | |
console.log(v1, v2, v3); | |
}); // do nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment