Last active
January 5, 2017 11:50
-
-
Save npetkov/ba7f3a81a19e30bc5dd537041c1cfa2f to your computer and use it in GitHub Desktop.
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
function Task(fork) { | |
return { | |
fork, | |
map: (mapRejector, mapResolver) => Task((reject, resolve) => { | |
fork(function() { | |
if (mapRejector) { | |
reject(mapRejector.apply(null, arguments)) | |
} else { | |
reject.apply(null, arguments) | |
} | |
}, function() { | |
if (mapResolver) { | |
resolve(mapResolver.apply(null, arguments)) | |
} else { | |
resolve.apply(null, arguments) | |
} | |
}) | |
}) | |
} | |
} | |
function mayEitherPassOrFail(reject, resolve) { | |
let resolveData = '{"foo":"1","bar":"2","baz":"3"}', | |
rejectData = '{"error":"Random reason"}' | |
let cancelToken = setTimeout(() => { | |
if (Math.random() < 0.5) { | |
resolve(resolveData) | |
} else { | |
reject(rejectData) | |
} | |
}, 500); | |
return () => clearTimeout(cancelToken) | |
} | |
var randomTask = Task(mayEitherPassOrFail) | |
var cancelFunction = randomTask | |
.map(string => JSON.parse(string), string => JSON.parse(string)) | |
.map(null, obj => Object.assign({}, obj, { newKey: 'newValue' })) | |
.fork(rejection => console.log(`The task was rejected with reason: ${rejection.error}`), | |
resolution => console.log(`Task completed with data keys: ${Object.keys(resolution)}`) | |
) | |
//cancelFunction(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment