Skip to content

Instantly share code, notes, and snippets.

@binura-g
Last active January 15, 2019 03:13
Show Gist options
  • Save binura-g/59dec19c62a75478b97c8cd9d6427b48 to your computer and use it in GitHub Desktop.
Save binura-g/59dec19c62a75478b97c8cd9d6427b48 to your computer and use it in GitHub Desktop.
Callback Hell example
const fs = require('fs');
const file = 'sample.txt';
// Execution Starts here
// We just want to read some data from a file, update it, write it back and read it again.
// This is what it will look like with callbacks - welcome to the Callback Hell!
read(file, data => {
console.log('READ-1:', data);
// Now we'll change the text.
const updatedData = `${data} - This has been updated!`;
// ...and update the same file.
write(file, updatedData, () => {
console.log('WRITE-1:', updatedData);
read(file, data => {
// Assume we'll be doing something different with the data this time.
// For now, let's just console.log it again.
console.log('READ-2:', data);
});
});
});
// This function writes the 'content' to the FILE
// and executes a callback after the write is completed.
function write(file, content, callback) {
fs.writeFile(file, content, err => {
if (err) console.log('Error:', err);
callback();
});
}
// This function reads from the file and
// passes the data into a callback function
function read(file, callback) {
fs.readFile(file, 'utf8', (err, data) => {
if (err) console.log('Error:', err);
callback(data);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment