Last active
March 29, 2017 14:37
-
-
Save ChillyBwoy/0210a16de2ccfa0e270a6baebcc82adc to your computer and use it in GitHub Desktop.
Promises Queue
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
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