main.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. const delay = (ms) => new Promise((resolve, reject) => setTimeout(() => resolve('Vika'), ms));
  2. function* likeAsync () {
  3. console.log(1);
  4. console.log(yield 1.5);
  5. let res1 = yield delay(2000);
  6. console.log(2, res1);
  7. let res2 = yield delay(2000);
  8. console.log(3, res2);
  9. try {
  10. console.log(yield fetch("http://localhost:10000"));
  11. }
  12. catch (e) {
  13. console.log('generator error catch', e);
  14. }
  15. let res3 = yield delay(2000);
  16. console.log(4, res3);
  17. let res4 = yield delay(2000);
  18. console.log(5, res4);
  19. }
  20. function run (gena) {
  21. let iter = gena();
  22. function next(result, error) {
  23. let value;
  24. let done;
  25. if (error) {
  26. const errGen = iter.throw(error);
  27. value = errGen.value;
  28. done = errGen.done;
  29. }
  30. if(!error) {
  31. const resultGen = iter.next(result);
  32. value = resultGen.value;
  33. done = resultGen.done;
  34. }
  35. if (done) {return};
  36. if(value && typeof value?.then === 'function'){
  37. value.then(next, err => next(undefined, err))
  38. } else {
  39. next(value);
  40. }
  41. }
  42. next();
  43. }
  44. run(likeAsync);