Skip to content

Instantly share code, notes, and snippets.

@plindberg
Created June 7, 2016 14:29
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 plindberg/a689a302614f2fdf4797ff1d99997d66 to your computer and use it in GitHub Desktop.
Save plindberg/a689a302614f2fdf4797ff1d99997d66 to your computer and use it in GitHub Desktop.
'use strict';
const co = require('co');
// Like `reduce()` but accepting a generator function, such that it can be used asynchronously
// within a generator function invoked by `co()`.
function* reduceg(arr, genfn, initial) {
let acc = initial;
for (let x of arr) {
acc = yield genfn(acc, x);
}
return acc;
}
// For the sake of illustration: Promise returning function that might do something asynchronous.
function process(x, reduction) {
return new Promise(resolve => {
if (x % 2 == 0) { //
setTimeout(() => {
reduction.push(`${x} hello async`);
resolve(true);
}, 1);
} else if (x % 3 == 0) {
reduction.push(`${x} hello sync`);
resolve(true);
} else {
resolve(false);
}
});
}
co(function *() {
let result = yield reduceg([1, 2, 3, 4, 5], function* (reduction, x) {
let processed = yield process(x, reduction);
if (!processed) {
reduction.push(`${x} NOT PROCESSED`);
}
return reduction;
}, []);
console.log(result);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment