Last active
January 24, 2018 22:18
-
-
Save aboutlo/b28b8c2c147540d8e0e8e685d793a95a to your computer and use it in GitHub Desktop.
A simple asyncPipe utility without any dependency to handle functions or promises
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
// Quick asyncPipe utility without any dependency | |
const asyncPipe = (f1, ...fns) => { | |
const toPromise = (fn, ...args) => | |
new Promise((resolve, reject) => { | |
try { | |
return resolve(fn(...args)); | |
} catch (e) { | |
return reject(e); | |
} | |
}); | |
const isPromise = p => typeof p.then === "function"; | |
return (...args) => | |
fns.reduce( | |
(res, fn) => res.then(fn), | |
(isPromise(f1) ? f1 : toPromise(f1, ...args)).then(() => f1(...args)) | |
); | |
}; | |
const add = a => parseInt(a, 10) + 1; | |
const asyncAdd = a => | |
new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(parseInt(a, 10) + 1); | |
}, 500); | |
}); | |
asyncPipe( | |
add, | |
asyncAdd, | |
asyncAdd | |
)(1).then(tot => console.log("4:", tot)); | |
// EXAMPLES | |
asyncPipe( | |
add, | |
asyncAdd, | |
add | |
)(1).then(tot => console.log("4:", tot)); | |
asyncPipe( | |
add | |
)(5).then(tot => console.log("6:", tot)); | |
asyncPipe( | |
asyncAdd | |
)(10).then(tot => console.log("11:", tot)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment