0

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?

9
  • 2
    Async functions only yield control when they reach an await, all you've done by adding async there is return a promise, not make anything actually asynchronous. Commented Sep 15, 2022 at 7:53
  • 1
    to be honest, you'd never write myReadFile2 like that ... return await somePromise for a start is just return somePromise - and since now that function has no await ... you wouldn't even make it async Commented Sep 15, 2022 at 7:53
  • In case 2 there is no await so the function will still block execution Commented Sep 15, 2022 at 7:54
  • One question per post please. Commented Sep 15, 2022 at 7:55
  • Thanks all for the comments! I see now that there are other questions that deal with this on here, and that, as @jonrsharpe pointed out immediately, control is relinquished from the async function when there is an await - I didn't know that. Thank you all! Commented Sep 15, 2022 at 8:00

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.