Last active
October 16, 2015 18:41
-
-
Save mkulke/6748257c8be63a4836e4 to your computer and use it in GitHub Desktop.
throttled es2015 promises
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
'use strict'; | |
var _ = require('underscore')._; | |
function promiseFactory (n) { | |
// return () => new Promise(resolve => resolve(n)); | |
// return () => new Promise(resolve => setTimeout(_.partial(resolve, n), 100)); | |
return () => new Promise(resolve => setTimeout(_.partial(resolve, n), _.random(1000))); | |
} | |
const errorThunk = function () { | |
return new Promise(() => { | |
throw new Error('WRONG!'); | |
}); | |
} | |
function throttledExecution(thunks, n) { | |
let resolveAll, rejectAll; | |
let counter = 0; | |
let results = _.times(thunks.length, _.noop); | |
function handleResolve (index, result) { | |
results[index] = _.constant(result); | |
if (counter < thunks.length) { | |
return executePromise(); | |
} else if (!_.contains(results, undefined)) { | |
resolveAll(_.map(results, fn => fn())); | |
} | |
} | |
function executePromise () { | |
let index = counter++; | |
const thunk = thunks[index]; | |
return thunk() | |
.then(_.partial(handleResolve, index)) | |
.catch(rejectAll); | |
} | |
return new Promise((resolve, reject) => { | |
resolveAll = resolve; | |
rejectAll = reject; | |
return Promise.all(_.times(_.min([n, thunks.length]), executePromise)); | |
}); | |
} | |
let someThunks = _.times(10, promiseFactory); | |
throttledExecution(someThunks, 3) | |
.then(console.log) | |
.then(_.partial(throttledExecution, someThunks.concat([errorThunk]), 2)) | |
.catch(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment