Created
July 28, 2016 17:37
-
-
Save peterforgacs/b11f96ede4d07e429d0ad4ca6cf75e60 to your computer and use it in GitHub Desktop.
Callback and Wrapper 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(filename, 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}`); | |
}); | |
// Promise and Callback Wrapper version | |
function readfile2(filename, callback) { | |
var p = new Promise(function (resolve, reject) { | |
FS.readFile(filename, function (err, data) { | |
// If callback | |
if (callback && typeof(callback) === 'function') { | |
if ( err ){ | |
return callback(err, data); | |
} | |
return callback (null, data); | |
} | |
// If promise | |
if (err) { | |
reject(err); | |
} | |
resolve(String(data)); | |
}); | |
}); | |
return p; | |
} | |
// Promise or Callback Wrapper | |
readfile2('file.txt', function (err, data) { | |
console.log(`Callback version ${data}`); | |
}); | |
readfile2('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