Skip to content

Instantly share code, notes, and snippets.

@bolasblack
Last active May 18, 2017 08:02
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 bolasblack/c98aee785cf5ff5c297e44c2e6314153 to your computer and use it in GitHub Desktop.
Save bolasblack/c98aee785cf5ff5c297e44c2e6314153 to your computer and use it in GitHub Desktop.
[Wirte once algorithm for sync & async function]
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