Guest User

Untitled

a guest
Jul 13th, 2024
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function delay(ms) {
  2.   return new Promise((resolve) => setTimeout(resolve, ms));
  3. }
  4.  
  5. const then = Date.now();
  6.  
  7. async function task(name, input) {
  8.   console.log(`[${Date.now() - then}] ${name}: start, input: ${input}`);
  9.   await delay(1_000);
  10.   console.log(`[${Date.now() - then}] ${name}: done, input: ${input}`);
  11.   return input + name;
  12. }
  13.  
  14. let token = 0;
  15. async function onUpdate(input) {
  16.   let current = ++token;
  17.   async function* gen() {
  18.     let result = await task('a', input);
  19.     yield;
  20.     result = await task('b', result);
  21.     yield;
  22.     result = await task('c', result);
  23.     console.log(`[${Date.now() - then}] final result: ${result}`);
  24.     return result;
  25.   }
  26.   for await (const _ of gen()) {
  27.     if (token !== current) break;
  28.   }
  29. }
  30.  
  31. onUpdate('1');
  32. await delay(500);
  33. onUpdate('2');
  34. await delay(2_000);
  35. onUpdate('3');
Advertisement
Add Comment
Please, Sign In to add comment