Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch APIs - Is it blocking or non-blocking code?

I've been looking at the Fetch API for a couple of days now.

While learning I came across the statement "using fetch() doesn't block your DOM " as it uses promises.

Happily moving forward with these tutorials and checking out some new ones, I saw a guy stating "using fetch() does block your DOM" in a presentation.

Can anyone educate me which one of the two it is?

like image 746
Pramesh Bajracharya Avatar asked Jul 29 '17 18:07

Pramesh Bajracharya


1 Answers

Using fetch in the sense of blocking/non-blocking code comes down to the difference between synchronous and asynchronous code.

One of JavaScript's design paradigms is called Run to Completion and it boils down to the fact that a piece of JS code that is currently executing cannot be interrupted by another piece of code. In other words, a function runs until it's finished, in a synchronous manner (also see the caveat in the end).

When you have code that is asynchronous, such as the one wrapped in a promise (which is what fetch is using), it gets scheduled to run later, after all the synchronous code is finished running, as well as after all other previously scheduled tasks (microtasks for promises).

This provides a gap in time that allows other parts of the system within which JS is running, such as the DOM in the browser, to freely operate on parts of the system that they share with the JavaScript engine, knowing JS won't get in their way.

Therefore, in the broadest sense, fetch is non-blocking and doesn't block the DOM.

It should be noted that promises represent synchronous code blocks connected via an asynchronous scheduling chain (the promise chain) so technically there are parts of fetch that do block the DOM but the overall process can be considered non-blocking for most purposes. See the answer by mpen for an example.


Note: after generators were introduced in ES6, a function stopped being the atomic execution unit in JavaScript. With yield and afterwards await, JS functions got the ability to break up into multiple async chunks of synchronously executing code.

like image 171
nem035 Avatar answered Sep 28 '22 07:09

nem035