I have two specific cases where I don't quite understand what's going on.
Case 1
// env = node.js
async function myReadFile1(...args) {
const {readFileSync} = require("fs")
return readFileSync(...args)
}
async function myReadFile2(...args) {
const {readFile} = require("fs/promises")
return await readFile(...args)
}
Question: are these two functions equivalent? If not, what is readFile
from fs/promises
doing differently to make it non blocking?
Case 2
// env = browser
<script>
function run() {
let x = 0
while (true) {
x++
}
}
run()
</script>
<script>
async function asyncRun() {
let x = 0
while (true) {
x++
}
}
asyncRun()
</script>
When I insert either one of these scripts into my index.html and open it with a browser, the page is non-responsive. With the first script
, I understand why. There's a blocking infinite loop. But with the second one, I understand it less. I naively thought that since it is an async function, it'd be non-blocking, with its own space in the event loop. Yet, the page is still unresponsive.
So clearly there's something about how async works that I'm missing and that I couldn't find any explaining resources for. Could someone point me in the right direction?