Skip to content

Instantly share code, notes, and snippets.

@rbuckton
Created July 24, 2019 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbuckton/f718883ffb0f22e64fcee0283e3e4ebc to your computer and use it in GitHub Desktop.
Save rbuckton/f718883ffb0f22e64fcee0283e3e4ebc to your computer and use it in GitHub Desktop.
try/using semantics
Symbol.asyncDispose = Symbol.for("Symbol.asyncDispose");
function __asyncUsing(obj) {
let state = obj !== null && obj !== undefined ? 0 : 2;
return {
[Symbol.asyncIterator]() { return this; },
async next() {
if (state) return this.return();
state = 1;
return { value: obj };
},
async return() {
if (state < 2) {
state = 2;
const asyncDispose = obj[Symbol.asyncDispose];
if (asyncDispose) {
await asyncDispose.call(obj);
}
else {
obj[Symbol.dispose]();
}
}
return { done: true };
}
};
}
class AsyncDisposable {
async [Symbol.asyncDispose]() {
console.log("start asyncDispose");
await Promise.resolve();
console.log("end asyncDispose");
}
}
async function main() {
console.log("before disposed");
for await (const _ of __asyncUsing(new AsyncDisposable())) {
console.log("do some work");
}
console.log("after disposed");
}
main();
Symbol.dispose = Symbol.for("Symbol.dispose");
function __using(obj) {
let state = obj !== null && obj !== undefined ? 0 : 2;
return {
[Symbol.iterator]() { return this; },
next() {
if (state) return this.return();
state = 1;
return { value: obj };
},
return() {
if (state < 2) {
state = 2;
obj[Symbol.dispose]();
}
return { done: true };
}
};
}
class Disposable {
[Symbol.dispose]() {
console.log("disposed");
}
}
console.log("before disposed");
for (const _ of __using(new Disposable())) {
console.log("do some work");
}
console.log("after disposed");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment