Defer
To ensure a function call is performed later in a program’s execution, usually for purposes of cleanup, we can use constructs in JavaScript that mimic similar behavior. In JavaScript, a common pattern is to use finally blocks for cleanup.
Suppose we wanted to create a file, write to it, and then close it when we’re done. Here’s how we can achieve that in JavaScript using the fs module and finally for cleanup.
To ensure a function call is performed later in a program’s execution, usually for purposes of cleanup, we can use constructs in JavaScript that mimic similar behavior. In JavaScript, a common pattern is to use `finally` blocks for cleanup.
Suppose we wanted to create a file, write to it, and then close it when we’re done. Here's how we can achieve that in JavaScript using the `fs` module and `finally` for cleanup.
Immediately after getting a file descriptor with `fs.openSync`, we ensure the closing of that file with `fs.closeSync` inside a `finally` block. This will be executed at the end of the try block, after `fs.writeFileSync` has finished.
```javascript
const fs = require('fs');
const path = '/tmp/defer.txt';
function createFile(path) {
console.log('creating');
let fd;
try {
fd = fs.openSync(path, 'w');
} catch (err) {
console.error('Error creating file:', err);
throw err;
}
return fd;
}
function writeFile(fd) {
console.log('writing');
fs.writeFileSync(fd, 'data');
}
function closeFile(fd) {
console.log('closing');
try {
fs.closeSync(fd);
} catch (err) {
console.error('Error closing file:', err);
process.exit(1);
}
}
function main() {
const fd = createFile(path);
try {
writeFile(fd);
} finally {
closeFile(fd);
}
}
main();It’s important to check for errors when closing a file, even in a deferred function. Running the program confirms that the file is closed after being written.
$ node defer.js
creating
writing
closingNow that we can run and build basic JavaScript programs, let’s learn more about the language.
Comments powered by Disqus