Last active
July 9, 2021 02:49
-
-
Save devcybiko/b55307b6e719360078c51e96ff4c1afe to your computer and use it in GitHub Desktop.
demonstration of how async/await is still asynchronous
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 { access } = require('fs').promises; | |
const { constants } = require('fs'); | |
const readline = require('readline'); | |
const prompt = require('prompt-sync')(); | |
let count = 10; | |
async function timer$(s) { | |
console.log(s + " " + count); | |
count--; | |
if (count) setTimeout(timer$, 1000, s); | |
} | |
async function access$(fname) { | |
try { | |
await access(fname, constants.R_OK | constants.W_OK); | |
console.log('can access'); | |
} catch { | |
console.error('cannot access'); | |
} | |
} | |
function questionExample() { | |
const name = prompt('What is your name?'); | |
console.log(`Hey there ${name}`); | |
} | |
function ask() { | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
return new Promise((resolve, reject) => { | |
rl.question('Enter input: ', (input) => { | |
rl.close(); | |
resolve(input); | |
}); | |
}); | |
} | |
async function questionExample$() { | |
const answer = await ask('What is your favorite food? '); | |
console.log(`Oh, so your favorite food is ${answer}`); | |
} | |
async function main$() { | |
let async = process.argv[2] === "async"; | |
await timer$("tick"); | |
if (async) await questionExample$(); | |
else questionExample(); | |
await access$("/etc/passwd"); | |
} | |
main$(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
asyncExample
This demonstrates that
async/await
performs asynchronously, despite the fact that the codelooks
synchronousWhen run with the
async
parameter everything is run asynchronously. Without it, thequestionExample()
function calls theprompt()
function which is synchronous and hangs the works.Run synchronously
node asyncExample.js
$
questionExample()
function is synchronousasync
parameter, thequestionExample()
is calledquestionExample()
calls theprompt()
function which is synchronous and hangs the works.timer$()
function doesn't continue to runRun asynchronously
node asyncExample.js async
$
questionExample$()
function is asynchronousasync
parameter, thequestionExample$()
function is calledquestionExample$()
calls readline.question() asynchronously