Usage for resource management?
dead-claudia opened this issue · 4 comments
More of a comment than a bug, but here's a use case I discovered playing around with async generators: resource management.
const fsp = require("fs-promise")
async function *open(file, opts) {
const fd = await fsp.open(file, opts)
try { yield fd } finally { await fsp.close(fd) }
}
for await (const fd of open("/path/to/file", {mode: "r+"})) {
const bit = await fsp.read(fd)
// do other things...
}
// descriptor automatically closed, so no resource leaks!
This seems correct to me, but a strange pun, and it would be unfortunate if it became common for things which would only yield once. Note that synchronous iterators permit the same. I think it'd be nice to look into a mechanism that's more targeted here for resource management, without mixing it with iteration.
@littledan I agree fully with that. It is a hack, and is most certainly counter-intuitive. I agree that resource management shouldn't be crossed with iteration like that, and should at least have a different syntax.
I was merely pointing out an interesting finding.
Yeah, this is interesting. Let's close this thread, as I don't think there's any particular action to take on this proposal.