Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function delay(ms) {
- return new Promise((resolve) => setTimeout(resolve, ms));
- }
- const then = Date.now();
- async function task(name, input) {
- console.log(`[${Date.now() - then}] ${name}: start, input: ${input}`);
- await delay(1_000);
- console.log(`[${Date.now() - then}] ${name}: done, input: ${input}`);
- return input + name;
- }
- let token = 0;
- async function onUpdate(input) {
- let current = ++token;
- async function* gen() {
- let result = await task('a', input);
- yield;
- result = await task('b', result);
- yield;
- result = await task('c', result);
- console.log(`[${Date.now() - then}] final result: ${result}`);
- return result;
- }
- for await (const _ of gen()) {
- if (token !== current) break;
- }
- }
- onUpdate('1');
- await delay(500);
- onUpdate('2');
- await delay(2_000);
- onUpdate('3');
Advertisement
Add Comment
Please, Sign In to add comment