Skip to content

Instantly share code, notes, and snippets.

@wizzard0
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wizzard0/d5083699110180e637d0 to your computer and use it in GitHub Desktop.
Save wizzard0/d5083699110180e637d0 to your computer and use it in GitHub Desktop.
разума сон чудовищ рождает
export function asyncReduce<T, TR>(list: T[], callback:
(prev: Promise<TR>, cur: T, i: number, list: T[], cont: (result: TR) => void,
aborter: (reason: any) => void, breaker: (result: TR) => void) => void,
interval?: number, initial?: TR): Promise<TR> {
return new Promise(function (resolveAll, rejectAll) {
var iv = interval || 100;
var res: TR = undefined;
var shouldSkip = false;
var breaker = function (r: TR) {
res = r;
shouldSkip = true;
resolveAll(r);
}
return list.reduce(function (p: Promise<TR>, c: T, i: number, arr: T[]) {
return p.then(function () {
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (shouldSkip) {
resolve(res);
} else {
try {
callback(p, c, i, arr, resolve, reject, function (tr) { breaker(tr); resolve(tr); });
} catch (e) {
console.log("exception in asyncReduce", i, c, e, list);
reject(e);
}
}
}, iv);
});
})
}, Promise.resolve(initial)).then(resolveAll);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment