Last active
October 18, 2019 12:53
-
-
Save nobishino/e97478b83dcaad38b250c76408c00628 to your computer and use it in GitHub Desktop.
Promiseであそんでみる
This file contains 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
/* | |
* Promiseはモナドじゃないらしいけどモナドっぽく書いてみる試み | |
* 次の3つの「Promiseを返す関数」をつなげてみる | |
* f :: number -> Promise number | |
* g :: number -> Promise string | |
* h :: string -> Promise () | |
*/ | |
const FAILURE_PROBABILITY = 0.1; //一定確率で各プロミスがrejectされるものとする | |
/** | |
* | |
* @param {number} x | |
* @returns {Promise<number>} | |
*/ | |
function f(x) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
r = Math.random() | |
if (r < FAILURE_PROBABILITY) { | |
reject("REJECTED"); | |
} else { | |
console.log("F: SUCCESS", x * r); | |
resolve(x * r); | |
} | |
}, 1000); | |
}); | |
} | |
/** | |
* | |
* @param {number} x | |
* @returns {Promise<string>} | |
*/ | |
function g(x) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
r = Math.random() | |
if (r < FAILURE_PROBABILITY) { | |
reject("REJECTED"); | |
} else { | |
msg = `New value = ${x * r}`; | |
console.log("G: SUCCESS", msg); | |
resolve(msg); | |
} | |
}, 1000); | |
}); | |
} | |
/** | |
* | |
* @param {string} msg | |
* @returns {Promise<()>} | |
*/ | |
function h(msg) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
r = Math.random() | |
if (r < FAILURE_PROBABILITY) { | |
reject("REJECTED"); | |
} else { | |
console.log("H: SUCCESS", msg); | |
resolve(); | |
} | |
}, 1000); | |
}); | |
} | |
//つなげるとこうなる | |
//なんか勘違いしてたけど単にこれでいい | |
f(1).then(g).then(h) | |
.catch(err => console.log(err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment