Created
June 7, 2016 14:29
-
-
Save plindberg/a689a302614f2fdf4797ff1d99997d66 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
'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