Skip to content

Instantly share code, notes, and snippets.

@ChillyBwoy
Last active March 29, 2017 14:37
Show Gist options
  • Save ChillyBwoy/0210a16de2ccfa0e270a6baebcc82adc to your computer and use it in GitHub Desktop.
Save ChillyBwoy/0210a16de2ccfa0e270a6baebcc82adc to your computer and use it in GitHub Desktop.
Promises Queue
function queue (operations, finished = []) {
let [curr, ...rest] = operations;
return !curr ? Promise.resolve(finished) : new Promise(resolve => {
curr()
.then(result => {
resolve(queue(rest, finished.concat(result)));
})
.catch(() => {
resolve(queue(rest, finished));
});
});
}
// sample
function f (expr) {
return () => new Promise((resolve, reject) => {
let rand = Math.random();
setTimeout(() => {
// ololo
(rand > 0.5) ? resolve(expr()) : reject();
}, rand);
});
}
let list = [1, 2, 3, 4, 5, 6, 7, 8, 9].map(x => f(() => x * x));
queue(list).then(data => {
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment