Last active
January 15, 2019 02:32
-
-
Save binura-g/b4a07e73e934630ea5483a60ac6c0d2c to your computer and use it in GitHub Desktop.
Async and Await 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"; | |
// Writes given text to a file asynchronously. | |
// Returns a Promise. | |
function write(text) { | |
return new Promise((resolve, reject) => { | |
fs.writeFile(FILE, text, err => { | |
if (err) reject(err); | |
else resolve(); | |
}); | |
}); | |
} | |
// Reads text from the file asynchronously and returns a Promise. | |
function read() { | |
return new Promise((resolve, reject) => { | |
fs.readFile(FILE, "utf8", (err, data) => { | |
if (err) reject(err); | |
else resolve(data); | |
}); | |
}); | |
} | |
// We can now run async non-blocking code | |
// as if it was 'normal' blocking code that | |
// we're used to seeing in other languages! | |
(async () => { | |
const originalContent = await read(); | |
console.log(originalContent); | |
await write("updated content"); | |
const updatedContent = await read(); | |
console.log(updatedContent); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment