Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
async/awaitとpromise使えばモナド糖衣構文っぽいの書けそうだよねって思って書いてみたけど、async () => {} でwrapしないといけないしまぁそんなにきれいに書けなかったって話。でもこういう邪悪なことやる関数型厨いそうですよね?(オマエだよ)
// 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
You can’t perform that action at this time.