Async JavaScript

Please help me in understanding async js, when we call fetch(url) the code of fetch begin to execute in background immediately ?, execute in background means it executes in another thread instead of main thread ? Is the name of another thread is event loop ?. or fetch block execute after the main thread has finished processing not in the background immediately.

Hello @Junaid_Arshad

fetch will start in another thread and would not block the main one and at the end it will success or fail

consider it as when you load page full of high resolution image and your internet not very fast so the page load and you can scroll and read the page while the image or some images still loading

1 Like

when we call fetch(url) the code of fetch begin to execute in background immediately

Yes, exactly.

execute in background means it executes in another thread instead of main thread ?

You don’t need to know where it executes :slight_smile: The important part is that it’s not blocking your page or your JavaScript. But yes, it will be executed in another thread.

Is the name of another thread is event loop ?

No, “event loop” is basically a mechanism for asking a thread to do something. When we talk about the “event loop” in Firefox, we typically mean “the main thread”, i.e. where most of your JavaScript code executes, where the DOM executes, etc.

or fetch block execute after the main thread has finished processing not in the background immediately.

Calling fetch doesn’t block anything. If you use await on the result, your current async function informs JavaScript that it is waiting until fetch is complete. So the async function is paused and other things can execute at the same time.

If you are familiar with cooperative multitasking, that’s what it is.

2 Likes

Thanks friends for help, I understand it. One thing i want to ask during learning javascript on mdn for example bouncing balls i feel that i also need to learn math for problem solving. I’m not a computer science student and i forget math which i learn when i’m in high school so there is need of learning math before javascript ?

That depends how far you wish to go.
For many uses of JavaScript, mathematics are not really necessary. Beyond some level, i.e. once you are writing complicated JavaScript that needs to run fast and/or limit the amount of memory it uses, the ability to think in mathematics (or in physics) definitely helps.

1 Like