0

My understanding is that javascript is single-threaded, meaning it will only execute one line at a time.

For the following code, why is 'await' necessary? I think it will still execute fetch before it moves to the next line:

const res = await fetch('http://testurl.com');

Can someone explain the importance of await in single-thread languages?

Thank you

Jin
  • 11
  • 1
    js is indeed single threaded, but it can also be async – Dan Jul 28 '21 at 21:54
  • Maybe this helps: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop – Felix Kling Jul 28 '21 at 21:56
  • Maybe too nitpicky, but: It's not right to think about it as being executed "one line at a time". What about `console.log( \n " foo" \n);` (where `\n` represent line breaks)? `console.log(` is not executed before `"foo"`, etc. Before evaluating code it is parsed into some other representation that represent statements and expressions. Those are executed one after the other. – Felix Kling Jul 28 '21 at 21:59

1 Answers1

0

Two types of functions can be 'paused' mid-function,

  • Async functions
  • Generator functions

So while you are correct, only 1 line will be executed at a time, await basically tells Javascript:

This function is now paused, and resume this function once this promise resolves.

While the function is paused, other code can run. But the 'only 1 line of code will run'-rule still holds.

Evert
  • 93,428
  • 18
  • 118
  • 189