Advertisement
TheUnproPro

Bootleg way for Async Iterators

Oct 18th, 2021
1,204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class AsyncIterator {
  2.     iterations = 0;
  3.     constructor(processor, iterations, callback) {
  4.         this.processor = processor;
  5.         this.callback = callback;
  6.         this.maxIterations = iterations;
  7.         this.tick();
  8.     }
  9.  
  10.     async tick() {
  11.         return new Promise((s, f) => {
  12.             setTimeout(() => {
  13.                 this.processor(this.iterations);
  14.                 s();
  15.             })
  16.  
  17.         }).then(() => {
  18.             if (this.iterations < this.maxIterations) {
  19.                 this.iterations++;
  20.                 this.tick();
  21.  
  22.             } else {
  23.                 this.callback()
  24.             }
  25.         })
  26.     }
  27. }
  28.  
  29. const iTest = new AsyncIterator(i => {
  30.     document.write(i + '<br>');
  31. }, 100, () => {
  32.     console.log('Done');
  33. })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement