Created
February 9, 2017 11:36
-
-
Save gnepud/f21486a5cdbcd84806b059af2ff4c9e2 to your computer and use it in GitHub Desktop.
Example: User Promise and Generator for handle async in Javascript
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
function run(generator, res) { | |
const ret = generator.next(res); | |
if (ret.done) return; | |
ret.value.then(function (res) { | |
run(generator, res); | |
}); | |
} | |
let count = 1; | |
function tick(time) { | |
return new Promise(resolve => { | |
setTimeout(() => { | |
console.log('tick %s after %s ms', count++, time); | |
resolve(); | |
}, time); | |
}); | |
} | |
function* main() { | |
console.log('start run...'); | |
yield tick(500); | |
yield tick(1000); | |
yield tick(2000); | |
} | |
run(main()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment