Skip to content

Instantly share code, notes, and snippets.

@psqq
Last active January 24, 2026 14:11
Show Gist options
  • Select an option

  • Save psqq/0acfa1c75294d68757f1a0b3d7893d30 to your computer and use it in GitHub Desktop.

Select an option

Save psqq/0acfa1c75294d68757f1a0b3d7893d30 to your computer and use it in GitHub Desktop.
import { setTimeout } from 'timers/promises';
/**
* @param {number} n
*/
async function range(n) {
let i = 0;
await setTimeout(100 * Math.random());
return {
[Symbol.asyncIterator]() {
return {
async next() {
await setTimeout(100 * Math.random());
i++;
return {
value: {
i,
async [Symbol.asyncDispose]() {
await setTimeout(1000 - 500 * i);
console.log('asyncDispose', i);
},
},
done: i >= n,
};
},
};
},
};
}
for await (await using x of await range(3)) {
console.log('x.i =', x.i);
}
/*
output:
x.i = 1
asyncDispose 1
x.i = 2
asyncDispose 2
*/
let i = 0;
for await (await using x of await ({
then(onFulfilled) {
onFulfilled({
[Symbol.asyncIterator]() {
return {
next() {
return {
value: {
[Symbol.dispose]() { console.log('dispose', i++) }
},
done: i > 2
}
}
}
}
});
}
})) {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment