Skip to content

Instantly share code, notes, and snippets.

@binura-g
Last active January 15, 2019 02:32
Show Gist options
  • Save binura-g/b4a07e73e934630ea5483a60ac6c0d2c to your computer and use it in GitHub Desktop.
Save binura-g/b4a07e73e934630ea5483a60ac6c0d2c to your computer and use it in GitHub Desktop.
Async and Await example 1
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