0

I'm currently reading 'Javascript: The Definitive Guide' and I have a question in relation to the asynchrony of the await keyword. In the book it states 'think of the await keyword as a marker that breaks up a function body into seperate synchronous chunks'. I presumed the only purpose of this would be to run each of them concurrently.

But in relation to the below example, the book states that 'fetching of the 2nd URL will not begin until the first fetch is complete'. And so I'm a bit confused as both statements seem contradictory. Any help would be appreciated. Thanks

let value1 = await getJSON(url1);
let value2 = await getJSON(url2);
Bryan
  • 63
  • 6
  • 1
    `await` doesn't *block*. It suspends the function execution thus allowing other code to run. Resuming after the awaited value is resolved. So, it's non-blocking. And it ensures that code `await f1(); await f2();` doesn't happen simultaneously but one after the other. No contradiction. – VLAZ Jun 05 '22 at 14:07
  • @VLAZ, Can you say more? I have never heard anybody call a function "non-blocking" unless that function is guaranteed to always _immediately_ return. But, I am thinking in terms of threads, and maybe you are talking about co-routines (I don't do Javascript.) Are you saying that `await ...` doesn't block the _thread_ in which the calling coroutine is running? – Solomon Slow Jun 05 '22 at 14:20
  • 1
    @SolomonSlow In JS most of the code runs on a single thread. Multi-threading is an opt-in. So when a function *blocks*, it means no other code gets to run as the thread is held up. Classic example is a busy loop - just a loop doesn't exist for certain length of time. If one of those runs on a page, then *nothing else works* while the loop does. Event handler such as clicks, hovers, etc. will be delayed and would only be executed after the loop ends. Non-blocking code does not hold up the thread. `await` doesn't it just suspends the execution of the current function and yields so other – VLAZ Jun 05 '22 at 14:29
  • 1
    @SolomonSlow functions can use the thread. Once the awaited value is available (the promise resolves), the suspended execution is resumed, and the function is added to the queue to executed when the thread stops being busy (in case something else is running). Once executed, it simply continues from where it left off. The entire execution context including already assigned variables is also restored. Thus `const a = 1; const b = await f(); return a + b;` may run for 2ms, even if `f()` needed 3 minutes to complete. – VLAZ Jun 05 '22 at 14:29

0 Answers0