Last active
November 19, 2024 18:32
-
-
Save James-E-A/be04f45f11346abafe3cf1f088886659 to your computer and use it in GitHub Desktop.
Javascript safe "Python-with like" pattern
This file contains hidden or 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
| /* pending https://github.com/tc39/proposal-explicit-resource-management */ | |
| /* Usage: | |
| let result = await use_resource({ | |
| async acquire(url) { | |
| // "__enter__" | |
| const e = document.createElement('iframe'); | |
| e.src = url; | |
| e.hidden = true; | |
| document.body.appendChild(e); | |
| return e; | |
| }, | |
| release(e) { | |
| debugger; // "__exit__" | |
| e.parentElement.removeChild(e); | |
| } | |
| }, async (e) => { // "with manager as e:" | |
| return await DO_STUFF_WITH(e); | |
| }, YOUR_IFRAME_RESOURCE_URL); | |
| */ | |
| export async function use_resource(manager, callback, ...acq_arg) { | |
| const resource = await manager.acquire(...acq_arg); | |
| try { | |
| return await callback(resource); | |
| } finally { | |
| manager.release(resource); | |
| } | |
| } | |
| export async function* use_iter_resource(manager, ...acq_arg) { | |
| const resource = await manager.acquire(...acq_arg); | |
| try { | |
| yield* resource; | |
| } finally { | |
| manager.release(resource); | |
| } | |
| } | |
| export function use_resource_sync(manager, callback, ...acq_arg) { | |
| const resource = manager.acquire(...acq_arg); | |
| try { | |
| return callback(resource); | |
| } finally { | |
| manager.release(resource); | |
| } | |
| } | |
| export function* use_iter_resource_sync(manager, ...acq_arg) { | |
| const resource = manager.acquire(...acq_arg); | |
| try { | |
| yield* resource; | |
| } finally { | |
| manager.release(resource); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment