Created
November 10, 2016 00:38
-
-
Save vojtatranta/8ab3bc87bba323423ab97348f9257d23 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// runtime, co se dá ukrýt | |
const composeAsync = (...fns) => { | |
const shiftedFns = fns.slice() | |
return (...args) => new Promise(resolve => resolve(...args)) | |
.then(compose.apply(this, shiftedFns.map(fn => promiseOrValue => { | |
if (promiseOrValue instanceof Promise) { | |
return promiseOrValue.then(fn) | |
} | |
return fn(promiseOrValue) | |
}))) | |
.then(promiseResult => { | |
if (promiseResult instanceof Error) { | |
return Promise.reject(promiseResult) | |
} | |
return promiseResult | |
}) | |
} | |
// --- hezká část --- // | |
// "čisté" funce | |
// db.get() vrací promise (ale nemusí a kod vypadá stejně) | |
const getPost = id => db.get('posts', id) | |
const parsePostBody = post => post.body | |
const resultOr404 = result => { | |
return (result ? result : | |
Object.assign(new Error('Not found'), { | |
code: 404, | |
}) | |
)} | |
const handlePostRequest = composeAsync( | |
getPost, | |
parsePostBody | |
resultOr404 | |
) | |
getPostBody(333).then(postBody => console.log(postBody)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment