Last active
May 18, 2017 08:02
-
-
Save bolasblack/c98aee785cf5ff5c297e44c2e6314153 to your computer and use it in GitHub Desktop.
[Wirte once algorithm for sync & async function]
This file contains hidden or 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
import co from 'co' // or whatever like co | |
import fetch from './fetch_data_synchronously' | |
import fetchAsync from './fetch_data_asynchronously' | |
export function process() { | |
const generator = processAlgorithmGenerator(fetch) | |
let next = { done: false } | |
while(!next.done) { | |
next = generator.next(next.value) | |
} | |
return next.value | |
} | |
export function processAsync() { | |
return co(processAlgorithmGenerator)(fetchAsync) | |
} | |
function* processAlgorithmGenerator(fetch) { | |
const nes = [] | |
let index = 0 | |
while (true) { | |
let ne = yield fetch(index) | |
if (!ne) break | |
nes.push(ne) | |
index += 1 | |
} | |
return nes | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment