Skip to content

Instantly share code, notes, and snippets.

@aboutlo
Last active January 24, 2018 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aboutlo/b28b8c2c147540d8e0e8e685d793a95a to your computer and use it in GitHub Desktop.
Save aboutlo/b28b8c2c147540d8e0e8e685d793a95a to your computer and use it in GitHub Desktop.
A simple asyncPipe utility without any dependency to handle functions or promises
// 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