Created
September 9, 2016 07:17
-
-
Save wesalvaro/3bb80e25dc713db30e99333a61a9c46f to your computer and use it in GitHub Desktop.
Pipelines asynchronous tasks by abstracting the recursive `setTimeout` calls.
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
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