Last active
August 29, 2015 14:05
-
-
Save wizzard0/d5083699110180e637d0 to your computer and use it in GitHub Desktop.
разума сон чудовищ рождает
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
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