Skip to content

Instantly share code, notes, and snippets.

@wesalvaro
Created September 9, 2016 07:17
Show Gist options
  • Save wesalvaro/3bb80e25dc713db30e99333a61a9c46f to your computer and use it in GitHub Desktop.
Save wesalvaro/3bb80e25dc713db30e99333a61a9c46f to your computer and use it in GitHub Desktop.
Pipelines asynchronous tasks by abstracting the recursive `setTimeout` calls.
const pipe = (...tasks) => {
const dominos = [];
const fellDomino = () => {
setTimeout(() => {
if (!dominos.length) return;
dominos.pop()();
}, 0);
};
tasks.forEach((task, i) => {
dominos.unshift(() => {
console.debug(`Domino ${i}`);
task();
fellDomino();
});
});
console.debug(`Lined up ${dominos.length} domino(s).`);
fellDomino();
};
// Example:
pipe(
console.log.bind(console, 'kick'),
console.log.bind(console, 'kick'),
console.log.bind(console, 'kick'),
console.log.bind(console, 'kick'),
console.log.bind(console, 'kick')
);
console.log('Next');
pipe(
console.log.bind(console, 'react'),
console.log.bind(console, 'react'),
console.log.bind(console, 'react'),
console.log.bind(console, 'react'),
console.log.bind(console, 'react')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment