Created
May 22, 2020 11:08
-
-
Save Sylvenas/66cc18b7664678b847f0fb56d5c81338 to your computer and use it in GitHub Desktop.
Functional programming Task async in parallel
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
// Task(functor,applicative,monad) | |
const Task = fork => ({ | |
map: f => Task((reject, resolve) => | |
fork(reject, a => resolve(f(a)))), | |
ap: fn => | |
Task((reject, resolve) => fork(reject, a => | |
fn.map(a).fork(reject, resolve) | |
)), | |
chain: f => | |
Task((reject, resolve) => fork(reject, a => | |
f(a).fork(reject, resolve))), | |
fork, | |
[Symbol.for('nodejs.util.inspect.custom')]: () => 'Task(?)' | |
}) | |
Task.of = a => Task((_, resolve) => resolve(a)) | |
// async get user name | |
const fetchName = Task((_, resolve) => { | |
setTimeout(() => { | |
resolve('James') | |
}, 2000) | |
}); | |
// async get user age | |
const fetchAge = Task((_, resolve) => { | |
setTimeout(() => { | |
resolve(20) | |
}, 2000) | |
}); | |
// pure app | |
const app = Task | |
.of(name => age => ({ name, age })) | |
.ap(fetchName) | |
.ap(fetchAge) | |
// effect | |
app.fork(() => { | |
console.log('something went wrong') | |
}, x => { | |
console.log('x', x) // log the user info | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment