Last active
December 5, 2017 11:48
-
-
Save joepie91/c6aa1ee552dcac821d03 to your computer and use it in GitHub Desktop.
Node.js callbacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require("fs"); | |
function readJSON(filename, callback) { | |
fs.readFile(filename, function(err, file) { | |
if (err != null) { | |
return callback(err); | |
} else { | |
var parsedFile = JSON.parse(file); | |
return callback(null, parsedFile) | |
} | |
}) | |
} | |
readJSON("./sample.json", function(err, parsedFile) { | |
if (err != null) { | |
console.log("It broke!", err); | |
} else { | |
console.log(parsedFile); | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Promise = require("bluebird"); | |
var fs = Promise.promisifyAll(require("fs")); | |
function readJSON(filename) { | |
return Promise.try(function(){ | |
return fs.readFileAsync(filename); | |
}).then(function(file){ | |
return JSON.parse(file); | |
}) | |
} | |
Promise.try(function(){ | |
return readJSON("./sample.json"); | |
}).then(function(parsedFile){ | |
console.log(parsedFile); | |
}).catch(function(err){ | |
console.log("It broke!", err); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment