generator.js 651 B

1234567891011121314151617181920212223242526272829
  1. const delay = ms => new Promise((ok, neOk) => setTimeout(() => ok(ms), ms))
  2. function run(gena) {
  3. let iter = gena()
  4. function next(promiseResult, error=false) {
  5. let a
  6. if (!error) {
  7. a = iter.next(promiseResult)
  8. } else {
  9. iter.throw(promiseResult)
  10. }
  11. if (a.value instanceof Promise) {
  12. a.value.then(result => next(result)).catch(e => next(e, true))
  13. }
  14. }
  15. next()
  16. }
  17. function* check() {
  18. console.log(1)
  19. let result1 = yield delay(1000)
  20. console.log(result1)
  21. let result2 = yield delay(2000)
  22. console.log(result2)
  23. return 100500
  24. }
  25. run(check)