Skip to content

Instantly share code, notes, and snippets.

@panthomakos
Created June 30, 2011 07:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panthomakos/1055795 to your computer and use it in GitHub Desktop.
Save panthomakos/1055795 to your computer and use it in GitHub Desktop.
Avoiding Nested Callbacks in Javascript
var fs = require('fs');
fs.mkdir('./hello',0777,makeDirectory);
function makeDirectory(err){
if (err) throw err;
fs.writeFile('./hello/world.txt', 'Hello!', writeFile);
}
function writeFile(err){
if (err) throw err;
console.log('File created with contents: ');
fs.readFile('./hello/world.txt', 'UTF-8', readFile);
}
function readFile(err, data){
if (err) throw err;
console.log(data);
}
var fs = require('fs');
function writeHello(){
return fs.writeFile('./hello.txt', 'Hello!', writeFile);
function writeFile(err){
if (err) throw err;
console.log('Wrote hello.txt');
}
}
function writeWorld(){
return fs.writeFile('./world.txt', 'World!', writeFile);
function writeFile(err){
if (err) throw err;
console.log('Wrote world.txt');
}
}
writeHello();
writeWorld();
var fs = require('fs');
fs.mkdir('./hello',0777,function(err){
if (err) throw err;
fs.writeFile('./hello/world.txt', 'Hello!', function(err){
if (err) throw err;
console.log('File created with contents: ');
fs.readFile('./hello/world.txt', 'UTF-8', function(err, data){
if (err) throw err;
console.log(data);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment