Created
January 29, 2018 16:10
-
-
Save binura-g/ec1e2f73d0ee0dbf05a68da9be8190b4 to your computer and use it in GitHub Desktop.
Promises Example 1
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
const fs = require("fs"); | |
const FILE = "sample.txt"; | |
// This function returns a promise that the 'text' we pass into | |
// this function has been asynchrnously written into our FILE. | |
const writePromise = text => { | |
return new Promise((resolve, reject) => { | |
fs.writeFile(FILE, text, err => { | |
if (err) reject(err); | |
else resolve(); | |
}); | |
}); | |
}; | |
// This function returns a promise that resolves to the the asynchronously | |
// read content in our FILE by fs.readFile | |
const readPromise = () => { | |
return new Promise((resolve, reject) => { | |
fs.readFile(FILE, "utf8", (err, data) => { | |
if (err) reject(err); | |
else resolve(data); | |
}); | |
}); | |
}; | |
// Now let's see how we'd run the same program | |
// with our promises. | |
// We just escaped the callback hell. We could chain more reads | |
// and writes and still have highly readable code. | |
readPromise() | |
.then(content => { | |
console.log(content); | |
return writePromise("updated content"); | |
}) | |
.then(() => { | |
return readPromise(); | |
}) | |
.then(updatedContent => { | |
console.log(updatedContent); | |
}) | |
.catch(err => console.log(err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment