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); } }); } }
ãããªMaybe ã¨ãOptionalã£ã½ããã¤ãç¨æãã¾ãã promise()
㧠Promiseãçæãã¦è¿ãããã«ãã¾ãããã£ã¦ãå¤ã«å¿ã㦠resolve
(JustãSome)ããã reject
(Nothing)ããããã¾ãã
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
asyncã®ä¸ã§ã promise()
ã awaitã§å¼ã³åºããã¨ã§ã doè¨æ³ã£ã½ãããâ¦â¦ã«è¦ããªãããªããªãã³ã¼ãã«ãªãã¾ãããã§ã失æç³»å¦çããªãå ´åã§ã catch
æ¸ãå¿
è¦ããã®ãã«ãã§ããï¼
try..catch
ãå¤ããã«ãã£ã¦ããããã«ãã¼ãå°å
¥ãã¾ããã
// introduce doM emulates do-like syntax sugar async function doM(f1, f2) { try { return f1(); } catch { if (f2) { return f2(); } } }
ãã® doM
ã« asyncãªç¡åé¢æ°ã渡ãã¨ããã®ä¸ã§doè¨æ³ã£ã½ãããâ¦â¦ã«è¦ããªãããªããªãã³ã¼ããæ¸ãã¾ãã
doM(async () => { const v1 = await o1.promise(); const v2 = await o2.promise(); console.log(v1, v2); }); // => foo bar doM(async () => { const v1 = await o1.promise(); const v2 = await o2.promise(); const v3 = await o3.promise(); console.log(v1, v2, v3); }); // do nothing
ã ããã©ãããã£ã¦è©±ã§ããããããããªã¢ãããä½ã£ã¦åæãã¦æ±ãå ´åã«ä¾¿å©ãããããªãã§ããããããã¢ããã¨ãJavaScriptã§ä½ããªã以ä¸