Created
June 5, 2018 13:01
-
-
Save tudorilisoi/7933a7bd3f444fa4fc2125cf86380887 to your computer and use it in GitHub Desktop.
Callbacks,promises and async/await
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
const fs = require('fs') //require the filesystem module: a standard node library | |
const util = require('util') | |
// const f = fs.readFile(__dirname + '/input.txt', { encoding: 'utf8' }) | |
// console.log('f is', f) | |
// process.exit() | |
const USER_FILENAME = __dirname + '/username.txt' | |
/* | |
//a callback hell | |
fs.readFile(USER_FILENAME, { encoding: 'utf8' }, | |
function handleResult(err, username) { | |
if (err) { | |
console.log('BUMMER', err.toString()) | |
return | |
} | |
console.log('GOT USERNAME FROM FILE:', username) | |
fs.readFile(__dirname + `/password-${username}.txt`, { encoding: 'utf8' }, | |
function handleResult(err, data) { | |
if (err) { | |
console.log('BUMMER', err.toString()) | |
return | |
} | |
console.log('GOT USERNAME FROM FILE:', data) | |
} | |
) | |
} | |
) | |
*/ | |
/* | |
const successHandler = username=> { | |
console.log(username) | |
return $.getJSON(`/api/password-${username}`) | |
} | |
const errorHandler = console.err.bind(console) | |
const passwordPromise = $.getJSON('/api/username') | |
passwordPromise | |
.then(successHandler) | |
.catch(err=>console.error(err.toString())) | |
//*/ | |
const readFileP = util.promisify(fs.readFile) | |
/* | |
//Promisified standard modules | |
const passwordPromise = readFileP(USER_FILENAME, { encoding: 'utf8' }) | |
.then(username=>readFileP(__dirname + `/password-${username}.txt`, { encoding: 'utf8' })) | |
passwordPromise | |
.then(data=>console.log('PASSWORD', data)) | |
.catch(err=>console.error(err.toString())) | |
*/ | |
function readUserNameP() { | |
return readFileP(USER_FILENAME, { encoding: 'utf8' }) | |
} | |
function readPasswordP(username) { | |
return readFileP(__dirname + `/password-${username}.txt`, { encoding: 'utf8' }) | |
} | |
async function main() { | |
try { | |
const username = await readUserNameP() | |
const password = await readPasswordP(username) | |
console.log(`USER: ${username}, PASS: ${password}`) | |
} catch (err) { | |
console.log('BUMMER', err.toString()) | |
//throw new Error ('DUNNO_WHAT_HAPPENED') | |
} | |
} | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment