Last active
March 6, 2020 22:08
-
-
Save rogerwelin/f898a90eabfdc5643c7543ad703d0a2f to your computer and use it in GitHub Desktop.
promises, async await
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'); | |
| // arrow functions.. These two are the same, but arrow functions are better | |
| fs.readFile(fileName, (err, data) => {}) | |
| fs.readFile(fileName, function(err, data){}) | |
| //doing many things concurrent at the same time | |
| async function getUsers() { | |
| // need this first so use await (array) | |
| let ids = await fetchJson("/friends/userid-123"); | |
| // this stuff is concurrent | |
| let promises = ids.map((id) >= { | |
| return fetchJson(`/users/${id}`); | |
| }); | |
| let friends = await Promises.all(promises); | |
| console.log(friends); | |
| } | |
| // regular callback-style - cannot return data, must nest callbacks | |
| function apa(fileName) { | |
| fs.readFile(fileName, 'utf-8', (err, data) => { | |
| if (err) throw err; | |
| console.log(data); | |
| }) | |
| } | |
| /* | |
| 2 async io functions. example using promises and async/await to avoid callback hell | |
| */ | |
| let readFileFrom = function(name, type) { | |
| return new Promise(function(resolve, reject) { | |
| fs.readFile(name, type, function(err, content) { | |
| if (err) | |
| reject(err) | |
| else | |
| resolve(content) | |
| }) | |
| }) | |
| } | |
| // writing the same function with arrow functions | |
| let apa2 = (fileName) => { | |
| return new Promise((resolve, reject) => { | |
| fs.readFile(fileName, 'utf-8', (err, data) => { | |
| if (err) | |
| reject(err) | |
| else | |
| resolve(data) | |
| }) | |
| }) | |
| } | |
| let writeData = function(name, content) { | |
| return new Promise(function(resolve, reject) { | |
| fs.writeFile(name, content, function(err) { | |
| if (err) | |
| reject(err) | |
| else | |
| resolve("ok!") | |
| }) | |
| }) | |
| } | |
| readFileFrom('package.json', 'utf-8').then(result => { | |
| return writeData('chaos.txt', result) | |
| }).then(result => { | |
| console.log(result) | |
| }).catch(err => { | |
| console.log(err) | |
| }) | |
| // doing the same thing but with async await | |
| async function doFileStuff() { | |
| try { | |
| let content = await readFileFrom('package.json', 'utf-8') | |
| resp = await writeData('chaos.txt', content) | |
| console.log('file stuff done' + resp) | |
| } catch(err) { | |
| console.log(err) | |
| } | |
| } | |
| doFileStuff() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment