Last active
March 21, 2019 19:25
-
-
Save mrm8488/e9b0a31a3ee077821b4f9499ad0560f9 to your computer and use it in GitHub Desktop.
Here we can see how Node.js 8 allow us to promisify I/O functions that return callbacks (without 3pp modules such as Q or Bluebird)
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
/* AUTHOR: mrm8488@gmail.com */ | |
/* Node.js v8 */ | |
const fs = require('fs'); | |
/* BEFORE util.promisify() */ | |
fs.writeFile('/tmp/test.js',"console.log('Hello world');", error => { | |
if(error) return console.log(error); | |
return console.log('file created successfully!') | |
}); | |
/* BEFORE util.promisify() handcrafted promise */ | |
const writeFilePromise = (file, data) => { | |
return new Promise((resolve,reject) => { | |
fs.writeFile(file ,data, error => { | |
if(error) reject(error); | |
resolve('file created successfully with handcrafted Promise!') | |
}); | |
}); | |
} | |
writeFilePromise('/tmp/test2.js', "console.log('Hello world with handcrafted promise!');") | |
.then(result => console.log(result)) | |
.catch(error => console.log(error)); | |
/* WITH util.promisify() (Node.js 8) */ | |
const util = require('util'); | |
const writeFile = util.promisify(fs.writeFile); | |
writeFile('/tmp/test3.js',"console.log('Hello world with promisify!');") | |
.then(() => console.log('file created successfully with promisify!')) | |
.catch(error => console.log(error)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment