Skip to content

Instantly share code, notes, and snippets.

@LionZXY
Created October 8, 2017 16:59
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 LionZXY/28c7b9c8e2d66a5c8e4800c74f859e7f to your computer and use it in GitHub Desktop.
Save LionZXY/28c7b9c8e2d66a5c8e4800c74f859e7f to your computer and use it in GitHub Desktop.
/**
* Асинхронный reduce
* @param {any[]} input
* @param {Function} iterator
* @param {any} initialValue
* @return {Promise}
*/
function asyncReduce(input, iterator, initialValue) {
let result = Promise.resolve(initialValue);
input.forEach((promise) => {
result = result.then((prevValue) =>
promise().then((value) =>
iterator(prevValue, value)
)
)
});
return result
}
let a = () => Promise.resolve('a');
let b = () => Promise.resolve('b');
let c = () => new Promise(resolve => setTimeout(() => resolve('c'), 100));
asyncReduce(
[a, c, b],
(acc, value) => [...acc, value],
['d']
).then(results => {
console.log(results); // ['d', 'a', 'c', 'b'];
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment