Created
July 24, 2019 17:17
-
-
Save rbuckton/f718883ffb0f22e64fcee0283e3e4ebc to your computer and use it in GitHub Desktop.
try/using semantics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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