Created
January 6, 2019 07:33
-
-
Save coderek/2078ef94db8710cac9623dc9fb1fbfe7 to your computer and use it in GitHub Desktop.
An object that track the progress of a series of async actions and support stop and resume
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
function Machine(data, done) { | |
let status = 'idle' | |
let progress = { | |
success: 0, | |
fail: 0, | |
total: data.length | |
} | |
function* process(data) { | |
for (const rec of data) { | |
const stopped = yield new Promise(res => { | |
setTimeout(() => res(Math.random() > 0.5)) | |
}, 200) | |
if (stopped) { | |
break | |
} | |
} | |
done(progress) | |
console.log('done'); | |
} | |
const y = process(data) | |
function tick() { | |
if (status === 'paused') { | |
return | |
} | |
let val = y.next(status === 'stopped') | |
if (!val.done) { | |
val.value.then(function (v) { | |
if (v) { | |
progress.success += 1 | |
} else { | |
progress.fail += 1 | |
} | |
setTimeout(tick) | |
}) | |
} | |
} | |
return { | |
start() { | |
status = 'running' | |
tick() | |
}, | |
pause() { | |
status = 'paused' | |
}, | |
stop() { | |
status = 'stopped' | |
}, | |
progress, | |
} | |
} | |
m = Machine([1,2,3,4,5,6], console.log) | |
m.start() | |
setTimeout(() => m.pause(), 700) | |
setTimeout(() => m.start(), 2000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment