Created
July 28, 2016 16:40
-
-
Save peterforgacs/f725ccc1666b67d96ce5a4a4214e7ca8 to your computer and use it in GitHub Desktop.
Callbacks vs Promises
This file contains hidden or 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
'use strict'; | |
var FS = require('fs'); | |
// Callback version | |
FS.readFile('file.txt', 'utf8', function (err, data) { | |
if (err) throw err; | |
console.log('File has been read:', data); | |
console.log | |
}); | |
console.log('After readFile.'); | |
// Promise wrapper version | |
function readfile(filename) { | |
return new Promise(function (resolve, reject) { | |
FS.readFile('file.txt', function (err, data) { | |
if (err) { | |
reject(err); | |
} | |
resolve(String(data)); | |
}); | |
}); | |
} | |
// Calling the promise wrapper version | |
readfile('file.txt') | |
.then(function (data) { | |
console.log(`File has been read: ${data}`); | |
return (data); | |
}) | |
.then(function (param) { | |
console.log(`After passing to the next ${param}`); | |
}) | |
.catch(function (error) { | |
console.log('Error has happened:', error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment