Skip to content

Instantly share code, notes, and snippets.

@Dmitriy-8-Kireev
Created January 15, 2019 21:57
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 Dmitriy-8-Kireev/207b516041a45c16930b0aa9a1dff3f8 to your computer and use it in GitHub Desktop.
Save Dmitriy-8-Kireev/207b516041a45c16930b0aa9a1dff3f8 to your computer and use it in GitHub Desktop.
JS Bin // source https://jsbin.com/tejajul
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
/**
* Асинхронный reduce
* @param {any[]} input
* @param {Function} iterator
* @param {any} initialValue
* @return {Promise}
*/
function asyncReduce(input, iterator, initialValue) {
let array = input.map(item => item());
return Promise.all(array).then(results => {
let acc = initialValue;
results.forEach(function(item, i, array) {
acc = iterator(acc, item);
});
return acc;
});
}
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'];
});
</script>
<script id="jsbin-source-javascript" type="text/javascript">/**
* Асинхронный reduce
* @param {any[]} input
* @param {Function} iterator
* @param {any} initialValue
* @return {Promise}
*/
function asyncReduce(input, iterator, initialValue) {
let array = input.map(item => item());
return Promise.all(array).then(results => {
let acc = initialValue;
results.forEach(function(item, i, array) {
acc = iterator(acc, item);
});
return acc;
});
}
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'];
});</script></body>
</html>
/**
* Асинхронный reduce
* @param {any[]} input
* @param {Function} iterator
* @param {any} initialValue
* @return {Promise}
*/
function asyncReduce(input, iterator, initialValue) {
let array = input.map(item => item());
return Promise.all(array).then(results => {
let acc = initialValue;
results.forEach(function(item, i, array) {
acc = iterator(acc, item);
});
return acc;
});
}
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