Created
October 8, 2017 16:59
-
-
Save LionZXY/28c7b9c8e2d66a5c8e4800c74f859e7f 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
/** | |
* Асинхронный 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