Write withConnection(work) that opens a (simulated) database connection, passes it to work, and always closes it – whether work succeeds, throws, or returns early – then show that no connection is left open.
Solution
main.js
let open = 0, nextId = 1;
function connect() {
open++;
const conn = { id: nextId++, query: (sql) => { if (sql.includes("DROP")) throw new Error("permission denied"); return 3; } };
console.log(` open #${conn.id}`);
return conn;
}
function withConnection(work) {
const conn = connect();
try {
return work(conn);
} finally {
open--; // runs on return AND on throw
console.log(` close #${conn.id}`);
}
}
for (const sql of ["SELECT * FROM quiz", "DROP TABLE quiz"]) {
try {
console.log(`${sql} → ${withConnection((c) => c.query(sql))} rows`);
} catch (e) {
console.log(`${sql} → error: ${e.message}`);
}
}
console.log("connections still open:", open);
Output Verified by running it on Node.js
open #1
close #1
SELECT * FROM quiz → 3 rows
open #2
close #2
DROP TABLE quiz → error: permission denied
connections still open: 0
The "with resource" pattern centralises cleanup: callers cannot forget to close, and finally runs before the result or error reaches them – which is why "close" prints first.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!