0

I understand asynchronous operations are put in an event que which runs after main thread has processed.

Do asynchronous operations partly load whilst main thread's being processed? If not, can we just conceive of asynchronous operations as being placed on the end of the main thread?

And when asynchronous operations do run, does the source order (vertical order they appear in a file) determine the order that they run in?

  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop – Ivar Jul 16 '20 at 16:12
  • Thanks @Scott Marcus. I can only conclude that asynchronous operations don't partly execute whilst main thread is processed; they execute after main thread's finished. Hope I'm right. And the answer you linked doesn't answer my second point – tonitone111 Jul 16 '20 at 17:14
  • All you really need to know to answer your questions is that JS is a single-threaded environment (there is only one thread) and the order that code within a function executes in doesn't change because the operation is asynchronous or not, you just need to understand the normal flow of code and it applies to any function. – Scott Marcus Jul 16 '20 at 17:22
  • A `fetch` that logs promise-object1 to console. A regular function that logs `5` to console. Another `fetch` that logs promise-object2 to console. In the console we get: 5, promise-object1, promise-object2. This would suggest regular source order determines in what order asynchronous functions execute. – tonitone111 Jul 16 '20 at 17:34
  • @tonitone111 but consider that if *two* asynchronous operations like `fetch()` are launched, the timing of when the responses are received determines when the `.then()` code runs. Ordering in the source is only a part of the picture. – Pointy Jul 16 '20 at 17:46
  • @Pointy Are you saying that, in the event que which deals with asynchronous operations, 1. Source-order and 2. The time it takes for a promise to resolve determine the sequence of execution of asynchronous operations? For instance, in my example, if the first fetch took a long time to resolve promise, the second fetch might execute before the first fetch? – tonitone111 Jul 16 '20 at 18:31
  • Yes, absolutely. Think of how dumb it would be if things didn't work that way. The completion of something like `fetch()` (an HTTP request) involves what amounts to an "event" when the response from the server is received by the browser. – Pointy Jul 16 '20 at 19:07

0 Answers0