index.js 835 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. function* likeFor(end, step = 1, start = 0) {
  2. for (let i = start; i < end; i += step) {
  3. yield i;
  4. }
  5. }
  6. function* twice() {
  7. yield* gena(10);
  8. yield* gena(20);
  9. }
  10. const delay = (ms) => new Promise((ok) => setTimeout(() => ok(ms), ms));
  11. function* likeAsync() {
  12. console.log(1);
  13. let res1 = yield delay(2000);
  14. console.log(2, res1);
  15. let res2 = yield delay(2000);
  16. console.log(3, res2);
  17. }
  18. function run(likeAsync) {
  19. let iter = likeAsync();
  20. function next(result, err) {
  21. let value, done;
  22. if (!err) {
  23. [{ value, done }] = [iter.next(result)];
  24. } else {
  25. [{ value, done }] = [iter.throw(err)];
  26. }
  27. if (done) return;
  28. if (value && typeof value?.then === "function") {
  29. value.then(next, (err) => next(undefined, err));
  30. } else {
  31. next(value);
  32. }
  33. }
  34. next();
  35. }
  36. run(likeAsync);