简体   繁体   中英

Does the fetch api happen outside of the main thread? if happening on the main thread how is it not blocking?

I am working on understanding asynchronous js, I know that promises, setTimeout, setInterval just "wait" for the main thread to free up and then they execute. Why is it that when a fetch happens it doesn't block ui like a while loop in a setTimeout would?

Let's take an example of a restaurant. The waiter is your main thread and the kitchen is your api. When you place an order, the waiter gives the details to the kitchen and continues to wait other tables (non-blocking). When the food is ready in the kitchen, the waiter gets notified and brings the food back to you (results are available in callback).

When you do a while loop it is similar to making the waiter stay at your table when you go over the menu. The waiter is made to do work and hence it is blocking.

Hope this analogy works.

When some other system is doing the work - in case of fetch the backend api is doing the work there will be no blocking when done asynchronously. The thread will continue to work on the next queued item.

When the main thread is doing the work - in case of while loop, it is done synchronously and will be blocking.

You can probably understand single-threaded async javascript best through:

Whether asynchronous I/O operations execute on the main thread depends largely on your environment. For example node uses multiple threads .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM